90 lines of code to implement the module packer

Magician Carson 2021-09-15 09:05:06
lines code implement module packer


Welcome to join Human high quality front end Framework Research Group , Take flight

Hello everyone , I'm Carson .

Today, let's talk about how to use 90 Line of code to achieve a modern JS Module packer .

Our packer is mini , But it did webpack Core functions .

and , I know you have a headache when you see large pieces of code , So this article is all pictures . After reading, if you are interested , Here is Warehouse address of complete code , Only 90 Line code .

Let's start happily .

Generate dependency graph

If the application is a ball of wool , Then the entry file is the thread header . The first thing the packer does is :

Start to filter the direction of the whole line along the end of the line

Suppose the entry file is entry.js

// entry.js
import a from './a.js';
import b from './b.js';
console.log(a, b);
 Copy code 

He depends on a.js And b.js.

em... It's a little too simple , Let's expand a.js And b.js

// a.js
import c from './c.js';
// ...
 Copy code 
// b.js
import d from './d.js';
import e from './e.js';
// ...
 Copy code 

So the whole dependency is like this :

The packer starts with the entry file , Trying to build a module ( namely js file ) The dependency between , That's what we just talked about Start to filter the direction of the whole line along the end of the line .

The dependencies between modules can be analyzed by import Statement statement hear .

In order to analyze import Statement statement , have access to babel And other compilation tools decompose the module code into AST( Abstract syntax tree ).

Traverse AST, The type is ImportDeclaration The node of is import Statement statement .

Last , We will AST Re convert to executable Object code , It may also need to be based on the hosting environment in which the code is to be executed ( It's usually a browser ) Do some conversion to the code .

such as , Browser does not support import './a.js' In this way ESM grammar , Then we need to put all ESM Grammatical transformation CJS grammar .

// Source code 
import './a.js';
// After the transformation 
require('./a.js');
 Copy code 

therefore , For the first mock exam (js file ), Will experience :

Right contains Object code and Dependencies between modules The data structure of is called asset.

Every asset Can pass Dependencies between modules Find the dependent module , Repeat the process , Generate a new asset, Finally, the whole application is formed asset The dependency between :

Applying complete dependencies is called Dependency graph (dependency graph).

Packaging code

Next , Just traverse Dependency graph , Will all asset Of Object code Just pack it together .

All the code will be packaged in one Immediate execution function in :

(function(modules) {
// Packaged code 
})(modules)
 Copy code 

modules All are saved in asset And their dependencies .

If you are right about modules Interested in the details of , You can turn the code in the warehouse at the end of the text

Just said ,asset Of Object code yes CJS canonical , similar :

// entry.js
require('./a.js');
require('./b.js');
 Copy code 

This means that we need to achieve :

  • require Method ( Other methods for introducing dependencies asset Of Object code

  • module object ( Used to save the current asset Of Object code Data exported after execution )

meanwhile , In order to prevent different asset Of Object code The variables in the are contaminated with each other , Every Object code A separate scope is required .

We will Object code Wrapped in function in :

// We operate on string templates 
`function (require, module, exports) { ${asset.code} }`
 Copy code 

therefore , The final packaging result is :

(function(modules) {
function require() {// ...}
require( entrance asset Of ID)
})(modules)
 Copy code 

This string is wrapped in the browser <script> tag , Will execute in turn :

  1. require( entrance asset Of ID), perform entrance asset Of Object code

  2. Object code Internally it will call require Carry out other asset Of Object code

  3. Step by step ...

summary

The packer works in two steps :

  1. Start traversing from the entry file , Generate Dependency graph

  2. According to dependency graph , Package the code into a Immediate execution function

This packer is still very young , Missing many necessary functions , such as :

  • Resolve circular dependency
  • cache

But the flaws don't hide the virtues ~

版权声明
本文为[Magician Carson]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/09/20210909142454919X.html

  1. Contrôle de l'arbre en vue converti en style de table
  2. CSS3 animation flash Effect
  3. Discuter des propriétés de la file d'attente pour l'événement bloc
  4. Node around USModules
  5. Webpack - - Premier aperçu (concept de base)
  6. Mise en œuvre du cadre de base mvvm par JS natif
  7. Calculer les propriétés par rapport aux auditeurs, etc.
  8. Configuration standard dockerfile et docker-composer.yml
  9. Collection de questions d'entrevue HTML
  10. Conteneur, définir la largeur et la hauteur ne répond pas?
  11. Introduction et syntaxe des objets (mise à jour à long terme)
  12. Bubble Mart invests in cat galaxy, which is a vertical e-commerce platform around the quadratic element
  13. Exigences et dépendances dans package-lock.json
  14. Mouvement tridimensionnel de la terre, du ciel et de la lune basé sur three.js
  15. Compréhension et analyse de l'objet de base JS
  16. Simple use of status data management (context, mobx, Redux)
  17. Simulated drumming
  18. Array method
  19. Performance optimization issue 03 - HTTP request optimization
  20. Vue learning -- watch listener
  21. Learn more about nexttick in Vue
  22. Talk about some moves used by vue3.0 in the project - External skill chapter (I)
  23. JavaScript genrator generator
  24. La dernière réponse à l'entrevue de développement Android, l'hiver froid de l'industrie
  25. Maserati's motorcycle has less than 10 in the world. It is definitely a work of art
  26. 2021 partage des questions du dernier examen écrit d'entrevue Android, pas d'accord
  27. Programmation asynchrone Java scirp, développement frontal de base
  28. 2021 dernier examen écrit d'entrevue Android, écrit trop bien
  29. Quels aspects doivent être pris en considération dans le tableau principal du distributeur libre - service?
  30. He inherited his mother's hundreds of millions of property for his boyfriend to squander. Unexpectedly, he was ruthlessly abandoned when he had 100 yuan left
  31. The fuel cost is half less than that of fuel vehicles at the same level. Is it really cheap to use song Pro DM?
  32. Le dernier résumé de l'expérience d'entrevue d'embauche de l'école Android de l'usine est nécessaire pour l'usine
  33. Le dernier dictionnaire avancé de programmeurs d'usine, l'expérience d'entrevue d'embauche de l'Agence de développement Android
  34. La dernière collection d'entrevues Android Golden nine Silver ten
  35. L'expérience d'entrevue de l'Ingénieur d'algorithme de saut d'octets, 2 mois d'entrevue Tencent, station B, Netease et ainsi de suite sur 11 entreprises résumé!
  36. La dernière collection d'entrevues d'Android Golden nine Silver ten recommande un projet github
  37. Yuan Li's recent situation revealed that he was obsessed with public welfare, dressed simply and fearless, grew fat, and married an 11-year-old husband
  38. Initial experience of template tool plop of [front end Engineering]
  39. Dernière question d'entrevue avancée et réponse d'Alibaba Android, Alibaba P8 vous apprendra en personne
  40. Partage des dernières questions d'entrevue pour Android haute fréquence, Introduction aux compétences d'entrevue pour le développement d'Android
  41. Partager les dernières questions d'entrevue Android haute fréquence avec quelques conseils
  42. About JavaScript modules
  43. Iteratable object and class arrays
  44. Function realization of Vue elementui exporting excel form
  45. Use canvas to realize a small screenshot function
  46. Object oriented programming (2)
  47. Several common value transfer methods between Vue components
  48. Démarrer avec le serveur de base zéro: Hello World
  49. J'a I construit un escalier pour aller sur la lune, combien de façons puis - je poursuivre la sœur Chang'e?
  50. CSS implémente la fonction d'expansion et d'arrimage du Texte multiligne
  51. Varlet CLI | vue3 Component Library Quick Prototyping Tool
  52. Belle vue sur les trois rivières Xiapu
  53. La partie Web qui déploie SharePoint ajoute son propre module de fonctionnalité
  54. React Native (mise à jour à long terme)
  55. La conception et le codage de l'arbre binaire requis pour chaque entrevue d'embauche de la société Java millet;
  56. 10 jours pour obtenir l'offre d'emploi Android d'Alibaba, entrevue Android
  57. A remporté avec succès Byte, Tencent, Pulse offer, 7 ans Java une expérience d'entrevue de baise,
  58. 10大前端常用算法,web应用与开发
  59. Nginx - minimum configuration! You deserve it
  60. Les questions d'entrevue couramment utilisées pour le cadre Java sont - elles prometteuses pour le développement Java?