目录
动手实现一个webpack的loader
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
{
// 模块或路径
loader: './css-loader.js',
options: {aaa: 111}
}
]
}
]
}
};
// css-loader.js
module.exports = function (source) {
console.log(this.getOptions()) // { aaa: 111 }
return `
const styleEl = document.createElement('style')
styleEl.innerText = ${JSON.stringify(source)}
document.head.appendChild(styleEl)
`
}
动手实现一个webpack的plugin
webpack 创建compiler对象,里面保存着webpack完整配置
↓
compiler
↓
compiler.run()
↓ 创建compilation对象,包含一次资源完整构建过程
compiler.compilation()
↓
compiler.make()---------------→compilation
| ↓
| compilation.buildModule()
| ↓
| compilation.seal()
| ↓
| compilation.optimize()
| ↓
| compilation.reviveChunks()
↓ ↓
compiler.afterCompile()←-------compilation.seal()
↓
compiler.emit()
↓
compiler.emitAssets() 最后将资源输出出去
const CustomWebpackPlugin = require('./custom-webpack-plugin')
module.exports = {
plugins: [
new CustomWebpackPlugin({bbb: 222})
]
};
class CustomWebpackPlugin {
constructor(options) {
this.options = options
}
/**
* 函数或类的原型上定义一个apply方法
* 注意:npm i -D @types/webpack
* @param {Compiler} compiler
*/
apply(compiler) {
// 文档地址:https://www.webpackjs.com/api/compiler-hooks/
// compiler.hooks.<钩子>.<钩子同步:tap;异步:tabAsync|tapPromise>
// tabAsync('插件名',(...,callback)=>{callback()})
// tapPromise('插件名',()=>{return Promise})
// 异步串行:多个相同的钩子,钩子按顺序调用(emit)
// 异步并行:多个相同的钩子,钩子无阻塞调用(make)
compiler.hooks.make.tapAsync("CustomWebpackPlugin",
/** @param {Compilation} compilation */
(compilation, callback) => {
compilation.hooks.seal.tap("CustomWebpackPlugin", () => {
})
callback()
})
}
}
module.exports = CustomWebpackPlugin
chrome浏览器调试nodejs代码
* 命令行执行:node --inspect-brk <filename>
* chrome浏览器F12打开控制台
* 点击控制台左上角nodejs图标
标签:CustomWebpackPlugin,plugin,compilation,module,loader,webpack,compiler
From: https://www.cnblogs.com/linding/p/18058812