import * as webpack from "webpack"; import { localIP } from "./utils"; export interface DevMapOptions { name: string; dllEntry: webpack.Entry; isProd: boolean; devPort?: number; } export default class MapPlugin { options: DevMapOptions; constructor(options: DevMapOptions) { this.options = options; } apply(compiler) { compiler.plugin("emit", (compilation, cb) => { const { name, dllEntry, isProd, devPort } = this.options; const { assets, chunks } = compilation.getStats().toJson(); const allAssets = chunks .filter(chunk => chunk.initial) .map(chunk => chunk.files[0]) as string[]; const end = Object.keys(dllEntry).length; const dllAssets = assets .reverse() .slice(0, end) .map(asset => asset.name); const mapContent = {}; const resource = {}; const namePrefix = isProd ? "" : `http://${localIP}:${devPort}/`; dllAssets.concat(allAssets).forEach((fullName: string) => { const name = fullName.split(".")[0].replace("js/", ""); const filePath = `${namePrefix}${fullName}`; mapContent[name] = filePath; resource[name] = filePath; }); const source = `var EZPackMap = ${JSON.stringify(mapContent)};`; compilation.assets[`${name}.js`] = { source: () => source, size: () => source.length }; const resourceContent = JSON.stringify(resource, null, 4); compilation.assets[`${name}.json`] = { source: () => resourceContent, size: () => resourceContent.length }; return cb(); }); } }