How to create a Webpack configuration
© https://webpack.js.org/

How to create a Webpack configuration

Most projects require a complex setup, use a configuration to handle this.

ByMario Kandut

This article is based on Node v18.13.0 and webpack v5.8.2

Starting with Version 4, webpack doesn't require any configuration. Although, most projects require a complex setup, and in that case a configuration file is much more efficient than typing all the commands manually in the terminal.

💰 The Pragmatic Programmer: journey to mastery. 💰 One of the best books in software development, sold over 200,000 times.

If you are unfamiliar with Webpack or want to refresh your knowledge, have a look at the webpack series:

Webpack Configuration Essentials

The configuration in webpack consists of multiple parts, see webpack docs. This article focuses on:

  • Language
  • Entry and Context
  • Output
  • Mode
  • Plugins
  • Cache

Configuration Languages

Webpack accepts configuration files written in multiple programming and data languages. It can handle different types of configuration files through the node-interpret package. A complete list of supported file extensions can be found in the node-interpret package.

In most scenarios, you will write a TypeScript or Babel/JSX configuration.

Typescript

To write the webpack configuration in TypeScript, you would first install the necessary dependencies, and the relevant type definitions.

npm install --save-dev typescript ts-node @types/node @types/webpack

And in your webpack.config.ts:

import path from 'path';
import webpack from 'webpack';
// in case you run into any typescript error when configuring `devServer`
import 'webpack-dev-server';

const config: webpack.Configuration = {
  mode: 'production',
  entry: './foo.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'foo.bundle.js',
  },
};

export default config;

Please check your tsconfig.json to include:

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true
  }
}

Additionally, you have to check your tsconfig.json file, if the module in compilerOptions in tsconfig.json is commonjs, This is needed, because ts-node does not support any module syntax other than commonjs.

Babel/JSX

In most cases, TypeScript or JavaScript will be used to write a configuration file for webpack. In some cases, also JSX (React JavaScript Markup) and Babel are used, to create a JSON configuration that webpack can understand.

First install your dependencies:

npm install --save-dev babel-register jsxobj babel-preset-es2015

Add a .babelrc file:

{
  "presets": ["es2015"]
}

Create a webpack.babel.config.js:

import jsxobj from 'jsxobj';

// example of an imported plugin
const CustomPlugin = (config) => ({
  ...config,
  name: 'custom-plugin',
});

export default (
  <webpack target="web" watch mode="production">
    <entry path="src/index.js" />
    <resolve>
      <alias
        {...{
          react: 'preact-compat',
          'react-dom': 'preact-compat',
        }}
      />
    </resolve>
    <plugins>
      <CustomPlugin foo="bar" />
    </plugins>
  </webpack>
);

Create a configuration for Webpack

In a nutshell, webpack is a static module bundler for modern JavaScript applications, and out of the box, you do not have to create a configuration file for webpack to work properly. For webpack to work, some assumptions are made.

Webpack will assume the following to work:

  • The entry point of your project is src/index.js and,
  • the output will be put in dist/main.js minified and optimized for production.

Let's start by creating an empty project and initialize webpack:

mkdir webpack-config
cd webpack-config
npm init -y
npm install --save-dev webpack webpack-cli

Create a file index.js, in src/index.js.

mkdir src
touch index.js

Add loadsh as a dependency and copy the following code into index.js:

npm i lodash
import _ from 'lodash';

function component() {
  const element = document.createElement('div');

  element.innerHTML = _.join(['Hello', 'webpack'], ' ');

  return element;
}

document.body.appendChild(component());

Now we have a basic project, with lodash as a dependency.

Let's create a webpack config for it:

touch webpack.config.js

And copy the following code into the config:

const path = require('path');

module.exports = {
  entry: {
    main: path.resolve(__dirname, './src/index.js'),
  },
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: '[name].bundle.js',
  },
};

TL;DR

Thanks for reading and if you have any questions, use the comment function or send me a message @mariokandut.

If you want to know more about Node, have a look at these Node Tutorials.

References (and Big thanks):

Webpack, StackShare, NodeJS, NPM, Smashing Magazine, Tania Rascia

More node articles:

How to create a Webpack configuration

Getting started with Webpack

How to list/debug npm packages?

How to specify a Node.js version

How to create a web server in Node.js

How to dynamically load ESM in CJS

How to convert a CJS module to an ESM

How to create a CJS module

How to stream to an HTTP response

How to handle binary data in Node.js?

How to use streams to ETL data?

How to connect streams with pipeline?

How to handle stream errors?

How to connect streams with pipe?

What Is a Node.js Stream?

Handling Errors in Node (asynchronous)

Handling Errors in Node.js (synchronous)

Introduction to errors in Node.js

Callback to promise-based functions

ETL: Load Data to Destination with Node.js

ETL: Transform Data with Node.js

ETL: Extract Data with Node.js

Event Emitters in Node.js

How to set up SSL locally with Node.js?

How to use async/await in Node.js

What is an API proxy?

How to make an API request in Node.js?

How does the Event Loop work in Node.js

How to wait for multiple Promises?

How to organize Node.js code

Understanding Promises in Node.js

How does the Node.js module system work?

Set up and test a .env file in Node

How to Use Environment Variables in Node

How to clean up node modules?

Restart a Node.js app automatically

How to update a Node dependency - NPM?

What are NPM scripts?

How to uninstall npm packages?

How to install npm packages?

How to create a package.json file?

What Is the Node.js ETL Pipeline?

What is data brokering in Node.js?

How to read and write JSON Files with Node.js?

What is package-lock.json?

How to install Node.js locally with nvm?

How to update Node.js?

How to check unused npm packages?

What is the Node.js fs module?

What is Semantic versioning?

The Basics of Package.json explained

How to patch an NPM dependency

What is NPM audit?

Beginner`s guide to NPM

Getting started with Node.js

Scroll to top ↑