案例实战之如何写一个webpack plugin
2021-05-13 22:28
标签:text apply info normal str OLE 源码 orm cto 案例实战之如何写一个webpack plugin 使用 生成的结果如下 [image-20191206173728326](F:\myobject\vue2\myb webpack 的源码compiler钩子函数是借助tapable库实现的 上面的钩子函数是在webpack解析代码的不同周期执行的 案例实战之如何写一个webpack plugin 标签:text apply info normal str OLE 源码 orm cto 原文地址:https://www.cnblogs.com/xinggood/p/11996934.html1.写一个生成打包文件目录的file.md文件
// 生成一个目录项目目录的文件夹
class FileListPlugin {
constructor(options) {
this.options = options
}
apply(compiler) {
compiler.hooks.emit.tap('fileListPlugin', (compilation) => {
let assets = compilation.assets
let content = 'In this build:\r\n'
Object.entries(assets).forEach(([fileName, fileSize]) => {
content += `--${fileName} —— ${Math.ceil(fileSize.size() / 1024)}kb\r\n`
})
console.log('====content====', content)
assets[this.options.filename] = {
source() {
return content
},
size() {
return content.length
}
}
})
}
}
module.exports = FileListPlugin
const FileListPlugin = require('./plugins/fileListPlugin.js')
plugins:[
new FileListPlugin({
filename: 'filelist.md'
}),
]
2.写一个生成版权信息的copyright文件的插件
class CopyRightWebpackPlugin {
constructor(options) {
this.options = options
}
apply(compiler) {
compiler.hooks.compile.tap('webpackCompiler', () => {
console.log('compiler')
})
compiler.hooks.emit.tapAsync('CopyRightWebpackPlugin', (compilation, cb) => {
compilation.assets[this.options.filename] = {
source() {
return 'copyRight by heibao'
},
size() {
return 25
}
}
cb()
})
}
}
module.exports = CopyRightWebpackPlugin
const {
Tapable,
SyncHook,
SyncBailHook,
AsyncParallelHook,
AsyncSeriesHook
} = require("tapable");
class Compiler extends Tapable {
constructor(context) {
super();
this.hooks = {
/** @type {SyncBailHook
上一篇:浅谈JS递归
下一篇:css代码乱码怎么解决
文章标题:案例实战之如何写一个webpack plugin
文章链接:http://soscw.com/index.php/essay/85335.html