Created
April 18, 2019 17:07
-
-
Save endiliey/b5a12b6302f0bb737f12bbcd28f5ceea to your computer and use it in GitHub Desktop.
InlineManifestHtmlWebpackPlugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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