TeaWeb/webpack/ManifestPlugin.ts

70 lines
2.1 KiB
TypeScript
Raw Normal View History

2020-03-31 01:27:59 +02:00
import * as webpack from "webpack";
import * as fs from "fs";
import * as path from "path";
2020-03-31 01:27:59 +02:00
interface Options {
file?: string;
base: string;
2020-03-31 01:27:59 +02:00
}
class ManifestGenerator {
private manifest_content;
readonly options: Options;
constructor(options: Options) {
this.options = options || { base: __dirname };
2020-03-31 01:27:59 +02:00
}
apply(compiler: webpack.Compiler) {
compiler.hooks.afterCompile.tap(this.constructor.name, compilation => {
const chunks_data = {};
for(const chunk_group of compilation.chunkGroups) {
const js_files = [];
const modules = [];
2020-03-31 01:27:59 +02:00
for(const chunk of chunk_group.chunks) {
if(chunk.files.length !== 1) throw "expected only one file per chunk";
js_files.push({
hash: chunk.hash,
file: chunk.files[0]
});
for(const module of chunk._modules) {
if(!module.type.startsWith("javascript/"))
continue;
if(!module.resource || !module.context)
continue;
if(module.context !== path.dirname(module.resource))
throw "invalid context/resource relation";
modules.push({
id: module.id,
context: path.relative(this.options.base, module.context).replace(/\\/g, "/"),
resource: path.basename(module.resource)
});
}
2020-03-31 01:27:59 +02:00
}
chunks_data[chunk_group.options.name] = {
files: js_files,
modules: modules
};
2020-03-31 01:27:59 +02:00
}
this.manifest_content = {
version: 2,
2020-03-31 01:27:59 +02:00
chunks: chunks_data
};
});
compiler.hooks.done.tap(this.constructor.name, () => {
fs.writeFileSync(this.options.file || "manifest.json", JSON.stringify(this.manifest_content));
});
}
}
export = ManifestGenerator;