在htmlWebpackPlugin和html-loader中使用<%= [variable] =>语法

sla*_*den 5 javascript webpack

使用Webpack 4以及HtmlWebpackPlugin和html-loader,我正在尝试:

  1. 从目录将其他html文件加载到index.html中
  2. 从htmlWebpackPlugin将变量加载到index.html

但是,当webpack.config.js中存在html-loader时,此方法不起作用。如果我可以使用首选的相同语法,但是我已经尝试使用${ }title标签,但是出现构建错误htmlWebpackPlugin undefined

index.html

<!doctype html>
<html>
    <head>
        <title><%= htmlWebpackPlugin.options.title %></title> <!-- this doesn't work -->
   <!-- <title>${htmlWebpackPlugin.options.title}</title>        //also doesn't work -->
    </head>
    <body>
        <section>${require("./path/to/other.html")}</section> <!-- this works fine -->
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
  entry: './src/main.js',
  devServer: {
    contentBase: './src',
    port: 4200,
    open: true
  },
  plugins: [
    new HtmlWebpackPlugin({
      hash: true,
      template: './src/index.html'},
      title: 'Index Page')
  ],
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        include: /src/,
        exclude: /node_modules/
      },
      {
        test: /\.(html)$/,
        exclude: /node_modules/,
        use: {
          loader: 'html-loader',
          options: {
            attrs:[':data-src'],
            minimize: false,
            conservativeCollapse: false,
            interpolate: true
          }
        }
      },
      {
        test: /\.css$/,
        use: [
          { loader: 'style-loader' },
          {
            loader: 'css-loader',
            options: {
              modules: true,
              localIdentName: '[path][name]__[local]--[hash:base64:5]'
            }
          }
        ]
      }
    ]
  },
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
}
Run Code Online (Sandbox Code Playgroud)

Ed'*_*'ka 2

可以通过按顺序堆叠以下加载器来实现:

{
  test: /\.html$/,
  use: [{
    loader: 'ejs-loader'
  }, {
    loader: 'extract-loader'
  }, {
    loader: 'html-loader',
    options: {
      interpolate: true
  }
}
Run Code Online (Sandbox Code Playgroud)

html-loader首先替换插入的片段,然后我们需要提取生成的 HTML - 这就是我们使用extract-loader然后ejs-loader替换ejs片段的原因,它确实看到了htmlWebpackPlugin变量。