Skip to content

Instantly share code, notes, and snippets.

@caiguanhao
Created March 15, 2020 17:20
Show Gist options
  • Save caiguanhao/e43c1e16ed4c3eb2226bd7e2390fc956 to your computer and use it in GitHub Desktop.
Save caiguanhao/e43c1e16ed4c3eb2226bd7e2390fc956 to your computer and use it in GitHub Desktop.
const { RawSource } = require('webpack-sources')
class WebpackAssetsManifest {
apply (compiler) {
compiler.hooks.emit.tapAsync('WebpackAssetsManifest', (compilation, callback) => {
let entrypoints = compilation.entrypoints
for (const [name, entrypoint] of entrypoints) {
const js = []
const css = []
entrypoint.getFiles().forEach(file => {
const ext = file.split('.').pop().toLowerCase()
if (ext === 'js') js.push(file)
else if (ext === 'css') css.push(file)
})
compilation.assets[compilation.getPath(`${name}-js.js`)] = new RawSource(`(function (arr) {
for (var i = 0; i < arr.length; i++) {
document.write('<script src="' + arr[i] + '"></script>');
}
})(${JSON.stringify(js)});`)
compilation.assets[compilation.getPath(`${name}-css.js`)] = new RawSource(`(function (arr) {
for (var i = 0; i < arr.length; i++) {
document.write('<link rel="stylesheet" media="screen" href="' + arr[i] + '" />');
}
})(${JSON.stringify(css)});`)
}
callback()
})
}
}
// vue.config.js
{
configureWebpack: {
plugins: [
new WebpackAssetsManifest({
entrypoints: true
})
]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment