Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

webpack打包原理 #81

Open
gdutwyg opened this issue Oct 23, 2019 · 0 comments
Open

webpack打包原理 #81

gdutwyg opened this issue Oct 23, 2019 · 0 comments
Labels

Comments

@gdutwyg
Copy link
Owner

gdutwyg commented Oct 23, 2019

webpack原理

webpack就是一个打包工具,识别你的入口文件,识别你的模块依赖,然后打包代码。至于,你是用es6的import,还是cmd或者amd,从webpack2开始,内置了对ES6、CommonJS、AMD 模块化语句的支持,webpack会对各种模块进行语法分析,并做转换编译。

loader原理

webpack打包那些资源文件(非js文件),会调用loader转成webpack能处理的模块。
在解析对于文件,会自动去调用响应的loader。loader 本质上是一个函数,输入参数是一个字符串,输出参数也是一个字符串。当然,输出的参数会被当成是 JS 代码,从而被 esprima 解析成 AST,触发进一步的依赖解析。webpack会按照从右到左的顺序执行loader。

Webpack 模块异步加载

默认webpack都是同步加载,但是如果文件一多,可能体验就不好了,所有,就有了异步加载的概念。那webpack是如何检测代码是异步的呢?

webpack有个require.ensure语法来标记为异步加载模块
新的webpack4推荐使用新的import() api(需要配合@babel/plugin-syntax-dynamic-import插件)

// require.ensure
require.ensure(['b'], function(require) {
  var c = require('c');
  // Do something special...
});

// import
import('lodash').then(_ => {
  // Do something with lodash (a.k.a '_')...
});

如何实现一个简单的webpack

  • 读取文件分析模块依赖
  • 对模块进行解析执行(深度遍历)
  • 针对不同的模块使用相应的loader
  • 编译模块,生成抽象语法树AST。
  • 循环遍历AST树,拼接输出js。

参考

webpack打包原理
Webpack 模块打包原理

@gdutwyg gdutwyg added the js label Oct 23, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant