Using html partials with webpack

123 Views Asked by At

I'm quite new in JS and webpack and I'm trying on my project to use partials for header and footer in order to not repeat them everywhere.

My first approach was to install html-loader and use in my index.html :

<%= require('html-loader!./assets/html/header.html') %>

It was working, only if I don't add any rule for html file in webpack config (I guess if I do it, it interfers with HtmlWebpackPlugin), however, my page is rendering :

[object Module]

and I don't find any good explanation on the web (related to a html file case).

Am I having a good approach, or there is another easier way to do it? I'm going to include these partials everywhere, but I don't exclude to create partials for things that I want to use in specific pages.

1

There are 1 best solutions below

4
On

the easier way is to use the html-bundler-webpack-plugin. This plugin supports many templating engines (Eta, EJS, Handlebars, Nunjucks, LiquidJS) "out of the box". The default template engine is fastest Eta (EJS like).

The simple usage, clean syntax, e.g., ./src/views/index.html

<html>
  <head>
    <!-- specify a source style file, relative to html file -->
    <link href="../scss/styles.scss" rel="stylesheet" />
    <!-- specify a source script file, relative to html file -->
    <script src="../js/main.js" defer="defer"></script>
  </head>
  <body>
    <!-- specify a source partial file, relative to project path -->
    <%~ include('/src/views/header.html') %>
    <h1>Hello World!</h1>
    <!-- specify a source image file, relative to html file -->
    <img src="../images/picture.png" />
    <!-- specify a source partial file, relative to project path -->
    <%~ include('/src/views/footer.html') %>
  </body>
</html>

The minimal Webpack config:

const HtmlBundlerPlugin = require('html-bundler-webpack-plugin');

module.exports = {
  plugins: [
    new HtmlBundlerPlugin({
      entry: {
        // define templates here
        index: './src/views/index.html', // => dist/index.html
      },
    }),
  ],
  module: {
    rules: [
      {
        test: /\.(css|sass|scss)$/,
        use: ['css-loader', 'sass-loader'],
      },
      {
        test: /\.(ico|png|jp?g|webp|svg)$/,
        type: 'asset/resource',
        generator: {
          filename: 'img/[name].[hash:8][ext]',
        },
      },
    ],
  },
};

Note The entry point is a HTML file. All source script and style files should be specified directly in HTML. The plugin resolves all source files in the HTML template and replaces the references with their output filenames in the generated HTML.

No additional plugins and loader required.