webpack-multiple-plugin
Version:
> 这是一个组成多页面Webpack的插件,基于``html-webpack-plugin``,内部使用了``ejs``插件进行模板编译
79 lines (76 loc) • 2.76 kB
text/typescript
import {
Chunk,
Compilation,
Compiler
} from "webpack";
const ConstDependency = require("webpack/lib/dependencies/ConstDependency");
const ConcatSource = require("webpack-sources").ConcatSource;
/**
* 将变量注入到js中
*/
class WebpackInjectVarPlugin {
options: any = {};
constructor(options: any) {
this.options = Object.assign(this.options, options);
}
apply(compiler: Compiler) {
let options = this.options;
compiler.hooks.compilation.tap(
"WebpackInjectVarPlugin",
(compilation) => {
// 生成依赖模模板,没有这个静态注入会报错
compilation.dependencyTemplates.set(
ConstDependency,
new ConstDependency.Template()
);
compilation.hooks.processAssets.tap(
{
name: "WebpackInjectVarPlugin",
stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
},
(assets) => {
let chunks: Set<Chunk> = compilation.chunks;
for (let chunk of chunks) {
// 获取页面的chunk信息与之对应
let chunkName: string = chunk.name;
let files: Set<string> = chunk.files;
let data: any = options.data;
let pageData: any = data[chunkName];
if (pageData) {
for (let file of files) {
// 仅仅处理js文件
if (/\.js$/.test(file)) {
// 获取资源的文件信息
let source : any = (<any>assets[file]).original();
// 方法参数
let args = [
"/*******************************",
"* PAGE INFO : " + pageData.path,
"*******************************/",
`window.PAGE_PATH = "${pageData.path}";`,
`window.PAGE_DATA = ${JSON.stringify(pageData.data)};`,
...source.getChildren()
];
/**
* 需要一个参数,source会根据这个参数生成子的source元素
*/
let sourcePre : any = new ConcatSource(
...args
);
/**
* 生成资源文件,便于开发
*/
sourcePre.sourceAndMap({ module: undefined });
// 渲染到文件
assets[file] = sourcePre;
}
}
}
}
}
);
}
);
}
}
export default WebpackInjectVarPlugin;