DEV Community

webdiscus
webdiscus

Posted on • Updated on

Keep output directory structure in Webpack

Some web projects may have many HTML templates that need to be compiled and placed in the output directory, e.g. dist/. When we have 5-10 pages we can easily define each page manually in the webpack config, but when we have 20-30 or more pages with a complex directory structure it can get tedious.

Luckily there is the HTML Bundler plugin for Webpack that read all files in the template directory and save compiled HTML files with the same structure in the output directory.

For example, there are templates in the src/views/ source directory:

src/views/index.html
src/views/about/index.html
src/views/news/sport/index.html
src/views/news/sport/hockey/index.html
src/views/news/sport/football/index.html
...
Enter fullscreen mode Exit fullscreen mode

We want to have the same folder structure in the dist/ directory:

dist/index.html
dist/about/index.html
dist/news/sport/index.html
dist/news/sport/hockey/index.html
dist/news/sport/football/index.html
...
Enter fullscreen mode Exit fullscreen mode

Just install the html-bundler-webpack-plugin:

npm install html-bundler-webpack-plugin --save-dev
Enter fullscreen mode Exit fullscreen mode

Add the plugin in the Webpack config:

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

module.exports = {
  plugins: [
    new HtmlBundlerPlugin({
      entry: 'src/views/', // the template directory
    }),
  ],
};
Enter fullscreen mode Exit fullscreen mode

All templates from the src/views/ directory will be compiled and saved in the dist/ directory with the same structure.

You can try the example in browser:

Open in StackBlitz

The plugin supports template engines such as Eta, EJS, Handlebars, Nunjucks "out of the box" without additional loaders and plugins.

P.S. This powerful plugin does not require additional plugins such as html-webpack-plugin, mini-css-extract-plugin.

Give HTML Bundler Plugin for Webpack a ⭐️ on GitHub

Top comments (0)