使用html-webpack-plugin将一个对象传递给ejs加载器

Passing an object to an ejs loader, using html-webpack-plugin

本文关键字:ejs 加载 html-webpack-plugin 一个对象 使用      更新时间:2023-09-26

我相信我到处都找遍了,但还是空手而归。我一直在使用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文件中使用。

in 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的参数中。

我也在寻找同样的东西。似乎模板可以访问作为htmlWebpackPlugin.options对象传递给html-webpack-plugin的选项对象。

包括;您需要从模板中将其引用为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 %>