Matthew
Matthew

Reputation: 962

Webpack to simply compile a bunch of Pug templates to HTML

Im getting started with webpack but one thing I cannot for the life of me work out is how to take a folder (with possible nested folders), full of .pug templates, and simply compile them to static html and put them in the output folder, maintaining any nested folder structure for each output html file that was in the source templates folder...

I dont want to have to manually specify each individual .pug file, and I definitely dont want webpack to try and parse the .pugs into JS and then attempt to require/import any of the imgs/fonts etc in the pug files and then complain about it, Im just after a basic, static 1:1 compile, pug file in, html file out. Why is it so hard to do that?

Upvotes: 5

Views: 7835

Answers (2)

RWDJ
RWDJ

Reputation: 816

This can be done very simply with only html-webpack-plugin and pug-loader.

webpack.config.js

const HTMLWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  // No javascript entrypoint to evaluate. Let the plugin do the heavy lifting
  entry: {},
  // Define how to translate Pug to HTML
  module: { rules: [ { test: /\.pug$/, use: 'pug-loader' } ] },
  // Generate the HTML file from template
  plugins: [ new HTMLWebpackPlugin({ template: './src/index.pug' }) ]
};

./src/index.pug

doctype html
html(lang="en")
  head
    include path/to/another.pug
...

Got this information from https://extri.co/2017/05/23/using-htmlwebpackplugin-and-pug/ and you can also go further to import css and javascript as normally done with html-webpack-plugin.

Upvotes: 1

Bryan Chen
Bryan Chen

Reputation: 46598

Use pug-html-loader to convert .pug to .html file. Use file-loader to copy the file to desired location. Don't use html-loader as you don't want to process resources used by the generated file.

You will end up something like this in your loader rules (untested, webpack 1 syntax, you may need to tweak it for webpack 2)

{
    test: /\.pug$/,
    loaders: ['file-loader?name=[path][name].html', 'pug-html-loader?pretty&exports=false']
}

Next you need to require all your pug files in your entry file

function requireAll (r) { r.keys().forEach(r); }
requireAll(require.context('./', true, /\.pug$/));

Upvotes: 11

Related Questions