skip to content
天真笔录

webpack插件

/ 1 min read

插件规范

插件通常为一个函数或者一个对象中包含了apply方法

实现

实现一个将sourcemap文件移动到sourcemap文件夹的功能

const path = require("path");
const fs = require("fs");
const glob = require("glob");

class OutPutSourceMapPlugin {
	apply(compiler) {
		compiler.hooks.afterEmit.tap("OutPutSourceMapPlugin", (compilation, callback) => {
			const entryFiles = glob.sync(path.resolve(__dirname, "./dist/*.js"));
			fs.mkdirSync("./sourcemap");
			entryFiles.forEach((file) => {
				const match = file.match(/dist\/(.+\.js)/);
				const pageName = match && match[1];
				fs.rename(file, `./sourcemap/${pageName}`, (err) => {
					if (err) throw err;
					console.log("Rename complete!");
				});
			});
		});
	}
}

module.exports = OutPutSourceMapPlugin;

使用

const OutPutSourceMap = require("./outputsourcemap");

module.export = {
	plugins: [new OutPutSourceMap()],
};

hooks 参考

https://webpack.docschina.org/api/compiler-hooks/