解决方案1
我找到了另一个解决方案,使用带有插入选项的html-loader.
https://github.com/webpack-contrib/html-loader#interpolation
{ test: /\.(html)$/,include: path.join(__dirname,'src/views'),use: {
loader: 'html-loader',options: {
interpolate: true
}
}
}
然后在html页面中你可以导入部分html和javascript变量.
${require('./partials/top.html')}
Home${require('./partials/nav.html')}
${require('../js/html-variables.js').hello}
${require('./partials/footer.html')}
唯一的缺点是您无法从HtmlWebpackPlugin导入其他变量,如此 (至少我找不到导入它们的方法)但对我来说这不是问题,只需在你的html中写标题或使用单独的javascript文件来处理变量.
解决方案2
老答案
不确定这是否适合您,但我将分享我的工作流程(在Webpack 3中测试).
而不是html-loader你可以使用这个插件github.com/bazilio91/ejs-compiled-loader:
{ test: /\.ejs$/,use: 'ejs-compiled-loader' }
将.ejs和你的HtmlWebpackPlugin中的.html文件更改为指向正确的.ejs模板:
new HtmlWebpackPlugin({
template: 'src/views/index.ejs',filename: 'index.html',title: 'Home',chunks: ['index']
})
您可以在.ejs文件中导入部分,变量和资源:
SRC /视图/谐音/ head.ejs:
SRC / JS / ejs_variables.js:
const hello = 'Hello!';
const bye = 'Bye!';
export {hello,bye}
SRC /视图/ index.ejs:
/>
注意,当您包含部分路径时,路径必须相对于项目的根目录.