Even if webpack is a bundler tool for JS, it can be extended to do pretty much everything.

Let’s see how we can configure webpack to parse and interpolate data inside .pug files.

Project set up

Create the package.json file Install webpack & webpack-cli & webpack-dev-server Create a src folder and a file app.js Create 3 scripts inside package.json Create a webpack.config.js file Create a simple configuration for webpack

— — — — — — — — — — — — — — — — — — — — — —

Create a new folder and inside it run this command to generate the package.json file:

npm init -y

-y will create the file without asking any questions

2. We need this modules only in development, so we will install them as dev dependencies

npm i -D webpack webpack-cli webpack-dev-server

This is the same with this:

npm install --save-dev webpack webpack-cli webpack-dev-server

3.

4. We need 3 scripts: one to run webpack in production mode, one to run it in development mode and one to start the development server

"scripts": { "build": "webpack --mode=production", "build:dev": "webpack --mode=development", "start:dev": "webpack-dev-server --mode=development" },

5.

6. If we want to run the webpack command both in development mode and production mode using our scripts then we must create a separate config object with the common configuration and then based on the arguments of the webpack command we will add diferent rules. In order to do this differentiation between production and development, then we must write in the following way

const path = require('path'); const config = {

entry: {

app: './src/app.js'

},

output: {

path: path.resolve(__dirname, 'dist'),

filename: "[name].bundle.js",

},

devServer: {

port: 3000,

}

}; module.exports = (env, argv) => { if (argv.mode === 'development') {}

if (argv.mode === 'production') {} return config;

}

With this, we defined an entry and output point for our application, the port for the development server and we created a simple boilerplate to figure it out whether we run the the webpack command in production or development mode. Even if we don’t need it for this short tutorial, it’s good to know how you can do it.

Add .pug support

Next let’s make webpack to read pug files and to load them in the distribution folder.

Install pug, pug-loader, html-webpack-plugin Create a file: index.pug with some dummy data. Write new rules in webpack.config.js file

— — — — — — — — — — — — — — — — — — — — — — —

pug module : read pug files; pug-loader: returns the file’s content as template function so we can interpolate data in our template; html-webpack-plugin: will get the index.pug file from src folder and using the other two loaders will emit a new index.html file in the dist folder

npm i -D pug pug-loader html-webpack-plugin

2. Inside the src folder create a new index.pug file and then create a simple layout inside it.