Search code examples
javascripthtmlwebpackejshtml-webpack-plugin

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


I believe I've looked everywhere, but I've come up empty handed. I've been using html-webpack-plugin to load a single index.html file from my source, but my client has come with some localisations, and I thought it would be great if I could add them dynamically.

So I'm trying to switch over to using a templating engine with html-webpack-plugin, namely ejs, but I'm having major problems!

I want html-webpack-plugin to render and .ejs file, and I need to give said .ejs file a huge object of localisations.

I want something like this:

<h1><%= header.title %></h1>

Coming from a localisation .json-file like this:

{
  "header": {
    "title": "My Clients Super Awesome Website"
  }
}

I've tried using two different ejs webpack loaders, and I simply can't figure out how to pass a simple object to the ejs loader, that I can use in my ejs file.

Hope you guys have some answers :D Thanks in advance.


Solution

  • in index.ejs

    <%= htmlWebpackPlugin.options.header.title %>
    

    in webpack.config.js

    module: {
        rules: [
        {
            test: /.ejs$/,
            loader: 'ejs-loader'
        }
    ]}
    

    and

    plugins: [
    new HtmlWebpackPlugin({
        header: {title: 'test'},
        template: './index.ejs',
    })]
    

    Notice. do not use options: { variable: 'data or xxx' } after ejs-loader, if variable is specified, htmlWebpackPlugin will be unknown.

    So you need use html-webpack-plugin in your webpack configuration. And put the object into HtmlWebpackPlugin's parameter.