[关闭]
@xiaoqq 2018-08-10T08:09:18.000000Z 字数 1667 阅读 1391

Webpack 自定义loader和plugins

Webpack


参考文章:

http://www.css88.com/doc/webpack/development/how-to-write-a-plugin/

1. 调试

a) 新建配置项,通过require方式引入

  1. var path = require('path');
  2. var webpack = require('webpack');
  3. var MyExampleWebpackPlugin = require('./wxplugin/index');
  4. var config = {
  5. devtool: "source-map",
  6. entry: {
  7. 'redpacket': './application/pages/activity180420/redPacket.js'
  8. },
  9. output: {
  10. path: path.resolve(__dirname, 'webapp/script'),
  11. filename: '[name].js'
  12. },
  13. module: {
  14. rules: [{
  15. test: /\.js/,
  16. use: [{
  17. loader: 'babel-loader',
  18. query: {
  19. presets: ['es2015', 'stage-0']
  20. }
  21. },
  22. path.resolve('./wxloader/wxjs.js')
  23. ]
  24. }]
  25. },
  26. plugins: [
  27. new MyExampleWebpackPlugin()
  28. ]
  29. };
  30. module.exports = config;

b) 安装node-nightly

c) 新建npm script

  1. "scripts": {
  2. "debug": "node-nightly --inspect-brk ./node_modules/webpack/bin/webpack.js"
  3. },

d) 新建vscode调试项,采用npm run script方式启动

  1. {
  2. "type": "node",
  3. "request": "launch",
  4. "name": "Launch via NPM",
  5. "runtimeExecutable": "npm",
  6. "runtimeArgs": [
  7. "run-script",
  8. "debug"
  9. ],
  10. "port": 9229
  11. }

2. 插件

插件是webpack的核心功能,需要理解一些 webpack 底层的内部特性来做相应的勾子。

a) Demo

  1. function HelloWorldPlugin(options) {
  2. // 使用配置(options)设置插件实例
  3. }
  4. HelloWorldPlugin.prototype.apply = function(compiler) {
  5. compiler.plugin('done', function() {
  6. console.log('Hello World!');
  7. });
  8. };
  9. module.exports = HelloWorldPlugin;

b) 编译器(Compiler)和编译(Compilation)

c) Hooks

执行顺序 Hook 作用
1 environment
2 afterEnvironment
3 entryOption 初始化入口选项
4 afterPlugins
5 afterResolvers
6 beforeRun
7 run 开始编译
8 normalModuleFactory
9 contextModuleFactory
10 beforeCompile
11 compile
12 thisCompilation
13 compilation
14 make 从entry开始递归的分析依赖,对每个依赖模块进行build
15 afterCompile
16 shouldEmit
17 emit 把各个chunk输出到结果文件
18 afterEmit
19 done

watch执行顺序

执行顺序 Hook 作用
6 invalid
7 watchRun
8 normalModuleFactory
9 contextModuleFactory
10 beforeCompile
11 compile
12 thisCompilation
13 compilation
14 make
15 afterCompile
16 shouldEmit
17 emit
18 afterEmit
19 done

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注