Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using <%=[variable]=> syntax with htmlWebpackPlugin AND html-loader

Using Webpack 4 and it's HtmlWebpackPlugin and html-loader together, I'm trying to:

  1. Load other html files into index.html from a directory
  2. Load variables into index.html from htmlWebpackPlugin

However, this doesn't work when html-loader is present in webpack.config.js. If I could use the same syntax that would be preferred, but I already tried using ${ } for the title tag but i get an build error, 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>

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')
  }
}
like image 389
slanden Avatar asked Apr 17 '18 22:04

slanden


1 Answers

It can be achieved by stacking up the following loaders in this sequence:

{
  test: /\.html$/,
  use: [{
    loader: 'ejs-loader'
  }, {
    loader: 'extract-loader'
  }, {
    loader: 'html-loader',
    options: {
      interpolate: true
  }
}

html-loader kicks in first replacing interpolated fragments, then we need to extract resulting HTML - that's why we use extract-loader and then ejs-loader can then replace ejs fragments and it does see htmlWebpackPlugin variables.

like image 117
Ed'ka Avatar answered Oct 29 '22 20:10

Ed'ka