javascriptwebpackpug-loader

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?


Solution

  • 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$/));