Last active
September 18, 2020 07:47
-
-
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.
This file contains hidden or 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
#!/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()); |
This file contains hidden or 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
{ | |
"scripts": { | |
"build": "NODE_ENV=production webpack --mode production && ./scripts/mergeHTML.js", | |
} | |
} |
This file contains hidden or 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 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