Skip to content

Instantly share code, notes, and snippets.

@endiliey
Created April 18, 2019 17:07
Show Gist options
  • Save endiliey/b5a12b6302f0bb737f12bbcd28f5ceea to your computer and use it in GitHub Desktop.
Save endiliey/b5a12b6302f0bb737f12bbcd28f5ceea to your computer and use it in GitHub Desktop.
InlineManifestHtmlWebpackPlugin
const fs = require('fs');
const path = require(`path`);
class InlineManifestHtmlWebpackPlugin {
constructor(options) {
this.options = Object.assign(
{manifestFileName: 'chunk-map.json', manifestVariable: '__chunkMapping'},
options,
);
}
apply(compiler) {
const outputPath = compiler.options.output.path;
const manifestPath = path.resolve(
outputPath,
this.options.manifestFileName,
);
const manifestVariable = this.options.manifestVariable;
const getManifest = () => {
if (fs.existsSync(manifestPath)) {
return JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
}
return null;
};
compiler.hooks.compilation.tap(
'InlineManifestHtmlWebpackPlugin',
compilation => {
compilation.hooks.htmlWebpackPluginAlterAssetTags.tapAsync(
'InlineManifestHtmlWebpackPlugin',
(htmlPluginData, callback) => {
const manifest = getManifest();
if (manifest) {
const newTag = {
tagName: 'script',
closeTag: true,
attributes: {
type: 'text/javascript',
},
innerHTML: `window.${manifestVariable}=${JSON.stringify(
manifest,
)}`,
};
htmlPluginData.head.unshift(newTag);
}
callback(null, htmlPluginData);
},
);
},
);
}
}
module.exports = InlineManifestHtmlWebpackPlugin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment