Webpack 4: The Complete Step by Step Guide

12
335
Webpack 4 Tutorial With Example From Scratch

At its core, webpack is a static module bundler for modern JavaScript applications. When webpack processes your application, it recursively builds a dependency graph that includes every module your application needs, then packages all of those modules into one or more bundles.

Related Post: Webpack Tutorial For Beginners.

Webpack 4 Improvements.

  • Performance improvements and faster build times (up to 98% faster)
  • Zero configuration for small apps. (You can check out the parceljs tutorial as well)
  • The better tree shaking for pure modules without side effects.
  • <script async>Support.
  • You can import and export web assembly (Rust, C++, C, etc.).
  • An introduction of the mode property which can take either development or production options and defaults to production.

Webpack 4 Example: Getting Started

It is incredibly configurable, but to get started, you only need to understand four Core Concepts:

  • Entry
  • Output
  • Loaders
  • Plugins

Entry

An entry point indicates which module webpack should use to begin building out its internal dependency graph. After entering the entry point, webpack will figure out which other modules and libraries that entry point depends on (directly and indirectly).

Here’s the simplest example of entry configuration:

// webpack.config.js

module.exports = {
  entry: './path/to/my/entry/file.js'
};

Output

The output property tells a webpack where to emit the bundles. It also creates and how to name these files. You can configure this part by specifying an output field in your configuration.

// webpack.config.js

const path = require('path');

module.exports = {
  entry: './path/to/my/entry/file.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'my-first-webpack.bundle.js'
  }
};

Loaders

Loaders enable webpack to process more than just JavaScript files. They allow you to leverage webpack’s bundling capabilities for all files by converting them to valid modules that webpack can process. Example of loaders is vue-loader, babel-loader, css-loader, etc.

// webpack.config.js

const path = require('path');

const config = {
  entry: './path/to/my/entry/file.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'my-first-webpack.bundle.js'
  },
  module: {
    rules: [
      { test: /\.txt$/, use: 'raw-loader' }
    ]
  }
};

module.exports = config;

Plugins

While loaders transform specific modules, plugins can be leveraged to perform a broader range of tasks. Plugins range from bundle optimization and minification to defining environment-like variables.

// webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin'); //installed via npm
const webpack = require('webpack'); //to access built-in plugins
const path = require('path');

const config = {
  entry: './path/to/my/entry/file.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'my-first-webpack.bundle.js'
  },
  module: {
    rules: [
      { test: /\.txt$/, use: 'raw-loader' }
    ]
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin(),
    new HtmlWebpackPlugin({template: './src/index.html'})
  ]
};

module.exports = config;

Start Webpack Project

Okay, so let us start with an example. First, we will create a project folder called a webpack starter.

Go into that folder, open the terminal, and hit the following command to generate a package.json file.

npm init

Now, we need to install the webpack. So let’s get it to install.

npm install webpack webpack-cli -D

So it will install the webpack and webpack-cli package as a development dependency.

Zero Configuration Webpack 4

If you have worked with the previous webpack version, we must create a webpack.config.js file. In this version of the webpack, which is 4, we do not need to create that file by default. Instead, we need to create one folder in the root called src, which needs to be defined in that index.js file. Though for more configuration, we need to create that file.

  1. Create one folder called src inside the root.
  2. In that folder, make one file called index.js.
  3. Write simple code in that file like a console.log(‘Webpack 4 is running without config file’);
  4. Run the webpack by going to the terminal and hitting this command: webpack.
  5. It will generate a dist folder, and inside that folder main.js file is created. Remember, by default, the build is production.

Webpack 4 Development and Production mode.

By default is a production mode. But we can generate the build in development mode as well. Go to your package.json file and add the following code inside the scripts object.

"scripts": {
    "dev": "webpack --mode development",
    "prod": "webpack --mode production"
},

Now for development mode, hit the following command.

npm run dev

For production mode, hit the following command.

npm run prod

Transpiling Javascript ES6 with Babel.

Modern Javascript is mostly written in ES6, and most of the latest browsers do not support it. So we need to transpile the ES6 code to the ES5 code.

Related Post: Beginner’s Guide To Setup  ES6 Development Environment

Webpack does not know how to transform, so we need the loaders to do the job.

babel-loader is the webpack loader for transpiling ES6 and above, down to ES5. So let us install the dependencies. First, we need to install a development dependency.

npm install babel-core babel-loader -D

Okay, now we need to configure the babel-loader. So first, create a file inside the root folder called webpack.config.js. Since the default configurations are already there, we need to define the babel-loader configuration.

// webpack.config.js

module.exports = {
   module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          use: {
            loader: "babel-loader"
          }
        }
      ]
   }
}

We need to install one more dependency on the development mode, a webpack-dev-server.

npm install webpack-dev-server -D

It provides us with a development server in which we can host our application in development. But, first, change the script in a package.json file.

"scripts": {
    "dev": "webpack-dev-server --mode development",
    "prod": "webpack --mode production"
},

Now, write the ES6 code inside the src  >>  index.js file.

// index.js

const app = (a, b) => {
   return a + b;
}

alert(app(4,5));

We have used an arrow function which is an ES6 feature. Now, in the root folder, create one file called index.html.

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Webpack 4 Tutorial</title>
</head>
<body>
   <div id="app"></div>
   <script src="main.js"></script>
</body>
</html>

Start the server with the following command.

npm run dev

Switch to http://localhost:8080. You can see that the Javascript file main.js is included correctly.

Configure React.js with Webpack 4

Now, for configuring React.js, we need to include the following dependency.

npm install babel-preset-react babel-preset-stage-0 -D

In the root folder, make one file called .babelrc.

{
   "presets": ["react", "stage-0"]
}

Install React.js.

The next step is to install the React.js dependencies.

npm install react react-dom --save

Inside the src folder, make one file called AppComponent.js.

// AppComponent.js

import React, { Component } from 'react';

export default class AppComponent extends Component {
   render() {
      return (
         <div>
            App Component is Rendered!!
         </div>
      )
   }
}

Okay, the React component is created. Next, include this AppComponent.js file inside an index.js file.

// index.js

import React from 'react';
import { render } from 'react-dom';
import AppComponent from './AppComponent';

render(<AppComponent />, document.getElementById('app'));

If you have not started the server, then start it.

npm run dev

You can see that at port: 8080, your web application is running.

That’s it for this tutorial.

12 Comments

  1. What needs to be done for running this example in production mode? Do I need to write a app.js file and use node server?

  2. What does the final webpack.config.js look like? Can you post this at the end of the article or host it on GitHub please?

  3. To my knowledge the uglify plugin was removed from webpack 4. At least I do get this error in the console:

    Error: webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead.

    Maybe you want to use a different plugin for this tutorial?

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.