Template in HTML, with Webpack, get error “variable” is not defined

ぐ巨炮叔叔 提交于 2019-12-05 23:28:34

The problem is that html-webpack-plugin uses the same template tags <%= %> to insert bundle information into template.

You have two options.

1. Change lodash.template delimiters

You could change delimiters used by client-side lodash/template to something else, so Webpack would ignore it. For example:

_.templateSettings.interpolate = /<\$=([\s\S]+?)\$>/g;

Check out this demo.

_.templateSettings.interpolate = /<\$=([\s\S]+?)\$>/g;

const temp = _.template
const titlePicDiscHalf = temp(document.getElementById('titlePicDiscHalf').innerHTML);

document.write(titlePicDiscHalf({ title: 'Hello World!' }));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>

<script type="text/template" id="titlePicDiscHalf">
  <div class="titlePicDiscHalf">
    <div class="picture"></div>
    <div class="title">
      <$=title$>
    </div>
    <div class="discription"></div>
    <div class="buttons"></div>
  </div>
</script>

2. Change html-webpack-plugin delimiters

Install ejs-loader separately and configure html-webpack-plugin to use it to load your template. There you can change delimiters to yours. It could look something like this:

plugins: [
  new HtmlWebpackPlugin({
    template: './index.html.ejs',
  })
],
module: {
  rules: [
    { test: /\.ejs$/, loader: 'ejs-loader', query: {
      interpolate: /<\$=([\s\S]+?)\$>/g,
      evaluate: /<\$([\s\S]+?)\$>/g,
    }},
  ]
},

Now, you can configure your template with two different set of delimiters, one for client bundle lodash template and another for html-webpack-plugin:

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title><$= htmlWebpackPlugin.options.title $></title>
  </head>
  <body>
    <script type="text/template" id="titlePicDiscHalf">
      <div class="titlePicDiscHalf">
        <div class="picture"></div>
        <div class="title"><%= title %></div>
        <div class="discription"></div>
        <div class="buttons"></div>
      </div>
    </script>
  </body>
</html>

Note, <title><$= htmlWebpackPlugin.options.title $></title> is used by webpack, and <div class="title"><%= title %></div> is by client-side lodash.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!