AppDividend
Latest Code Tutorials

Webpack 4 Tutorial With Example From Scratch

20,062

Get real time updates directly on you device, subscribe now.

 Webpack 4 Tutorial With Example From Scratch is today’s topic. 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. I have try my best to understand webpack 4 tutorial as easy as possible.

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 parceljs tutorial as well)
  • The better tree shaking for pure modules without side effects.
  • <script async>Support.
  • By default, 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 Tutorial: 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 webpack where to emit the bundles.  It also creates and how to name these files. You can configure this part by specifying a 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 give you the ability to leverage webpack’s bundling capabilities for all kinds of 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 are used to transform certain types of modules, plugins can be leveraged to perform a broader range of tasks. Plugins range from bundle optimization and minification all the way 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 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 previous webpack version, then we have to create a webpack.config.js file. In this version of webpack which is 4, we do not need to create that file by default. We just need to create one folder in root called src and in that index.js file needs to be defined. 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 call index.js.
  3. Write simple code in that file like console.log(‘Webpack 4 is running without config file’);
  4. Run the webpack by going to terminal and hit this command: webpack.
  5. It will generate 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 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.

Related Posts
1 of 5
npm run prod

Transpiling Javascript ES6 with Babel.

All the modern Javascript is mostly written in ES6, and most of the latest browsers are not supporting it. So we need to transpile the ES6 code to ES5 code.

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

Webpack does not know how to make the transformation, so we need the loaders to get a job done.

babel-loader is the webpack loader for transpiling ES6 and above, down to ES5. So let us install the dependencies. We need to install as 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 just need to define the babel-loader configuration.

// webpack.config.js

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

Now, we need to install one more dependency for the development mode, and that is webpack-dev-server.

npm install webpack-dev-server -D

It provides us the development server in which we can host our application in development. 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 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 the http://localhost:8080 You can see that 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.

Next step is to install the React.js dependencies.

npm install react react-dom --save

Inside 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, 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.

Finally, Webpack 4 Tutorial With Example From Scratch is over. Thanks for taking.

11 Comments
  1. Vivek Vaibhav says

    Very helpful tutorial for understanding the webpack. Thank you so much.

  2. Ronald Newcomb says

    Where does main.js in index.html come from? Is that a typo for index.js?

    1. Krunal says

      It is the output from webpack. main.js file build after webpack compile the index.js file.

  3. Mr. Bajaj says

    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?

    1. Bryan says

      You would run the ‘prod’ npm script that’s in package.json:
      npm run prod

  4. sr charles spencer says

    very helpful man. thanks a lot!

  5. vijay chandrakant pawar says

    Please use ‘babel-preset-env’ Instead of ‘babel-preset-stage-0’

  6. Daniel says

    Noob question: Why is there no dependency “babel-preset-env”? In other tutorials it is often included,

  7. RajaSekhar says

    Thanks a lot man 🙂

  8. Tom says

    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?

  9. Jerry Mandering says

    Appreciate you taking the time to write this.

Leave A Reply

Your email address will not be published.

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