[英]How to get both EJS compilation and html-loader in html-webpack-plugin?
[英]Passing an object to an ejs loader, using html-webpack-plugin
我相信我到处都是,但我空手而归。 我一直在使用html-webpack-plugin
从我的源码加载一个index.html
文件,但我的客户端已经有了一些本地化,我认为如果我可以动态添加它们会很棒。
所以我试图切换到使用带有html-webpack-plugin
的模板引擎,即ejs
,但我遇到了重大问题!
我想要html-webpack-plugin
来渲染和.ejs
文件,我需要给.ejs
文件一个巨大的本地化对象。
我想要这样的东西:
<h1><%= header.title %></h1>
来自本地化.json
文件,如下所示:
{
"header": {
"title": "My Clients Super Awesome Website"
}
}
我尝试过使用两个不同的ejs webpack加载器,我根本无法弄清楚如何将一个简单的对象传递给ejs加载器,我可以在我的ejs文件中使用它。
希望你们有一些答案:D提前谢谢。
在index.ejs中
<%= htmlWebpackPlugin.options.header.title %>
在webpack.config.js中
module: {
rules: [
{
test: /.ejs$/,
loader: 'ejs-loader'
}
]}
和
plugins: [
new HtmlWebpackPlugin({
header: {title: 'test'},
template: './index.ejs',
})]
注意。 不要在ejs-loader
之后使用options: { variable: 'data or xxx' }
,如果指定了变量, htmlWebpackPlugin
将是未知的。
因此,您需要在webpack配置中使用html-webpack-plugin。 并将该对象放入HtmlWebpackPlugin的参数中。
我在寻找同样的事情。 好像模板可以访问传递给html-webpack-plugin的选项对象作为htmlWebpackPlugin.options
对象。
包括例如。 标题,你需要从模板中引用它作为htmlWebpackPlugin.options.title
。 我不知道是否有任何方式以更多插件无关的方式传递值,因此您可以在模板文件中引用title
作为title
。
容易插入任何参数。
// webpack.config.js
...
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'template/index.ejs',
templateParameters: {
'title': 'My Clients Super Awesome Website',
'episode: '2'
}
}),
...
<!-- index.ejs -->
<%= title %>
<%= episode %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.