Webpack如何向JSP、Apache Velocity等服务端模板注入带哈希的JS bundle名
解决方案
该需求完全可以通过Webpack实现,无需依赖会校验HTML结构的插件,通过轻量的自定义Webpack插件即可快速实现,具体步骤如下:
1. 配置基础打包规则
首先确保Webpack基础配置可正常生成带哈希后缀的JS bundle,示例webpack.config.js基础配置:
const path = require('path'); const fs = require('fs'); module.exports = { entry: './src/index.js', output: { // 配置生成带8位内容哈希的bundle文件名 filename: 'index.[contenthash:8].js', path: path.resolve(__dirname, 'dist'), // Webpack5原生支持打包前清空dist目录,Webpack4可引入clean-webpack-plugin实现 clean: true }, // 其他loader、devServer等配置按需补充 plugins: [] };
2. 添加自定义插件处理Velocity模板
直接在配置文件中新增自定义插件,作用是在Webpack打包完成、拿到最终bundle文件名后,批量读取VM模板、替换JS引用路径、输出到dist目录,完整插件代码及注册逻辑如下:
// 自定义插件定义,放在webpack.config.js顶部即可 class ReplaceVmScriptPlugin { apply(compiler) { // 监听Webpack编译完成的钩子,此时已确定所有bundle的最终文件名 compiler.hooks.done.tap('ReplaceVmScriptPlugin', (stats) => { // 获取生成的JS bundle文件名 const allAssets = stats.toJson().assets; const targetBundle = allAssets.find(asset => asset.name.startsWith('index.') && asset.name.endsWith('.js') ).name; // 列出需要处理的所有VM模板文件名 const vmFileList = ['index.vm', 'login.vm']; vmFileList.forEach(fileName => { // 读取源VM模板内容 const originContent = fs.readFileSync( path.resolve(__dirname, 'src', fileName), 'utf8' ); // 替换模板中的JS引用路径,如需全局匹配多处分可以用正则:/src="index\.js"/g const updatedContent = originContent.replace( 'src="index.js"', `src="${targetBundle}"` ); // 将处理后的模板输出到dist目录 fs.writeFileSync( path.resolve(__dirname, 'dist', fileName), updatedContent, 'utf8' ); }) }) } } // 在plugins数组中注册自定义插件 module.exports = { // 原有entry、output等配置不变 plugins: [ new ReplaceVmScriptPlugin() ] }
3. 执行打包验证
运行npx webpack命令后,即可在dist目录得到预期产物:带哈希的JS bundle、已替换JS引用路径的VM模板文件。如果有多入口打包需求,只需调整插件中匹配bundle文件名的逻辑,即可支持多bundle路径的批量替换。
内容的提问来源于stack exchange,提问作者KevSheedy
相关产品推荐
相关产品推荐

