Skip to content

Instantly share code, notes, and snippets.

@agoldis
Last active September 18, 2020 07:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agoldis/21782f3b9395f78d28dce23e3b6ddd56 to your computer and use it in GitHub Desktop.
Save agoldis/21782f3b9395f78d28dce23e3b6ddd56 to your computer and use it in GitHub Desktop.
Load modern and legacy scripts. Add multiple webpack targets into a single html file. html-webpack-plugin does not support merging multiple webpack targets. This naive and simple solution generates 2 html files and merges script tag into index.html.
#!/usr/bin/env node
const { readFileSync, writeFileSync } = require('fs');
const { parse } = require('node-html-parser');
const { resolve } = require('path');
const modernPath = resolve(__dirname, '..', 'dist', 'modern.html');
const legacyPath = resolve(__dirname, '..', 'dist', 'legacy.html');
const outputPath = resolve(__dirname, '..', 'dist', 'index.html');
const legacyHTML = parse(readFileSync(legacyPath));
const modernHTML = parse(readFileSync(modernPath));
const legacyScripts = legacyHTML.querySelectorAll('[data-flag="merge"]');
const modernScript = modernHTML.querySelector('[data-flag="merge"]');
legacyScripts.forEach((s) => {
modernScript.parentNode.appendChild(s);
});
writeFileSync(outputPath, modernHTML.toString());
{
"scripts": {
"build": "NODE_ENV=production webpack --mode production && ./scripts/mergeHTML.js",
}
}
const getPlugins = (htmlFileName) => [
new HtmlWebpackPlugin({
inject: true,
template: 'public/index.html',
filename: htmlFileName,
}),
new ScriptExtHtmlWebpackPlugin({
module: /\.mjs$/,
custom: [
{
test: /\.js$/,
attribute: 'nomodule',
},
{
test: /\.m?js$/,
attribute: 'data-flag',
value: 'merge',
},
],
})
]
const legacyConfig = {
output: {
publicPath: '/',
filename: '[name].[chunkhash].js',
},
plugins: getPlugins('legacy.html')
}
const modernConfig = {
output: {
publicPath: '/',
filename: '[name].[chunkhash].js',
},
plugins: getPlugins('modern.html')
}
module.exports = [legacyConfig, modernConfig]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment