我们换一种思路,对添加备注进行实现。
准备工作
本文的工程环境承接上文
这个简单的工程目录如下:
- build
- node_modules
- package.json
- plugins
- 0.createLicense.js
- 1.createFileList.js
- 2.createLicense.js
- 3.addRemark.js
- loaders
- src
- index.js
- index.html
- LICENSE
简单分析
上一节的思路是:
- 我想在index.html里面加点内容,那好,我等着你生成一个主页文件,最后我再来改改。
现在,我们不妨这样思考:
- 我想在index.html里面加点内容,那好,这个主页文件是HTML插件生成的吧,我让它这么这么改。
要按这个思路实现,我们得知道html-webpack-plugin给我们留了些什么接口,于是很自然的,去这个插件的仓库看看。 于是,在ReadMe里找的下面案例:
// If your plugin is direct dependent to the html webpack plugin:
const HtmlWebpackPlugin = require('html-webpack-plugin');
// If your plugin is using html-webpack-plugin as an optional dependency
// you can use https://github.com/tallesl/node-safe-require instead:
const HtmlWebpackPlugin = require('safe-require')('html-webpack-plugin');
class MyPlugin {
apply (compiler) {
compiler.hooks.compilation.tap('MyPlugin', (compilation) => {
console.log('The compiler is starting a new compilation...')
// Static Plugin interface |compilation |HOOK NAME | register listener
HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tapAsync(
'MyPlugin', // <-- Set a meaningful name here for stacktraces
(data, cb) => {
// Manipulate the content
data.html += 'The Magic Footer'
// Tell webpack to move on
cb(null, data)
}
)
})
}
}
module.exports = MyPlugin
好了,现在可以照猫画虎了。
插件实现
const pluginName = 'AddRemarksPlugin';
const HtmlWebpackPlugin = require('html-webpack-plugin');
class AddRemarksPlugin {
constructor(options = {}) {
this.remarks = options.remarks || '<!-- 这是一条由AddRemarksPlugin生成的默认备注 -->'
}
apply(compiler) {
const { hooks, options, webpack } = compiler;
const outputPath = options.output.path
compiler.hooks.thisCompilation.tap(pluginName, (compilation) => {
HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tapAsync(
pluginName,
(data, cb) => {
const raw = data.html
const start = raw.indexOf('<head>') + 6
const left = raw.substring(0, start)
const right = raw.substring(start)
data.html = `${left}\n${this.remarks}\n${right}`
cb(null, data)
}
)
});
}
}
module.exports = AddRemarksPlugin;
源代码
https://github.com/nicennnnnnnlee/webpack-plugin-loader-examples