Getting Started with Webpack [With Example Project]

Webpack is a module bundler that facilitates building formidable JavaScript applications. It has gained critical traction given a React village chose it as a categorical build tool. Webpack is neither a package manager nor a charge runner as it uses a opposite (more advanced) approach, though a idea is also to set adult a energetic build process.

Webpack works with vanilla JavaScript. You can use it to bundle a immobile resources of an application, such as images, fonts, stylesheets, scripts into one singular record while taking caring of all a dependencies.

You won’t need Webpack to emanate a elementary app or website, for instance one that has customarily one JavaScript and one CSS record and a few images, however it can be a life-saver for a more formidable focus with several resources and dependencies.

Webpack bundlerWebpack bundler

Webpack vs. charge runners vs. Browserify

So, how does Webpack smoke-stack adult compared to other build tools such as Grunt, Gulp, or Browserify?

Grunt and Gulp are charge runners. In their config file, we specify a tasks, and a charge curtain executes them. The workflow of a charge runner fundamentally looks like this:

Task curtain workflowTask curtain workflow
IMAGE: pro-react.com

However, Webpack is a module bundler that analyzes a whole project, sets adult a dependency tree, and creates a bundled JavaScript file that it serves to a browser.

Webpack workflowWebpack workflow
IMAGE: pro-react.com

Browserify is closer to Webpack than charge runners, as it also creates a dependency graph though it does so customarily for JavaScript modules. Webpack goes one step further, and it doesn’t customarily gold source formula though also other assets such as images, stylesheets, fonts, etc.

If we wish to know some-more on how Webpack compares to other build tools, we suggest we dual articles:

  1. Andrew Ray’s Webpack: When to Use and Why on his possess blog
  2. Cory House’s Browserify vs Webpack on freeCodeCamp (with overwhelming illustrations)

The dual illustrations above are from a Webpack materials of a Pro React handbook, another apparatus that’s value a look.

Four core concepts of Webpack

Webpack has four categorical pattern options called “core concepts” that we will need to conclude in a growth process:

  1. Entry – a starting point of a dependency graph (one or some-more JavaScript files).
  2. Output – a record where we wish a output to be bundled to (one JavaScript file).
  3. Loaders – transformations on a resources that turn them into Webpack modules so that they can be added to a dependency graph. For instance, css-loader is used for a import of CSS files.
  4. Plugins – tradition actions and functionalities performed on a bundle. For instance, a i18n-webpack-plugin embeds localization into a bundle.

Loaders work on a per-file basement before a gathering takes place. Plugins are executed on a bundled code, at a finish of a gathering process.

Install Webpack

To install Webpack, open a command-line, navigate to your plan folder, and run a following command:

npm init

If we don’t wish to do a pattern yourself, we can make npm populate a package.json record with a default values with a following command:

npm init -y

Next, implement Webpack:

npm implement webpack --save-dev

If we have used a default values this is how your package.json record should demeanour like now (the properties can be in a opposite order):

{
  "name": "_tests",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "dependencies": {
    "webpack": "^3.6.0"
  },
  "devDependencies": {
    "webpack": "^3.6.0"
  },
  "scripts": {
    "test": "echo "Error: no exam specified"  exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Create a pattern file

You need to emanate a webpack.config.js record in a base folder of a project. This configuration file has a executive role, as this is where we will define a 4 core concepts (entry points, output, loaders, plugins).

The webpack.config.js record holds a pattern object of that properties we need to specify. In this article, we will mention a 4 properties that correspond to a 4 core concepts (entry, output, module, and plugin), though a config intent has other properties as well.

1. Create a entrance point(s)

You can have one or some-more entrance points. You need to conclude them in a entry property.

Insert a following formula dash into a webpack.config.js file. It specifies one entrance point:

module.exports = {
  entry: "./src/script.js"
};

To mention more than one entrance points we can use either a array or a intent syntax.

In your plan folder, create a new src folder and a script.js record inside it. This will be your entry point. For contrast purposes, only place a string inside it. we used a following one (however, we can also use a some-more engaging one):

const nod = "Hi. I'm a Webpack starter project.";
document.write(greeting);

2. Define a output

You can have only one outlay file. Webpack bundles all a resources into this file. You need to configure a output skill in a following way:

const trail = require("path");

module.exports = {
  entry: "./src/script.js",
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, 'dist')
  }
};

The filename skill defines a name of a bundled file, while a path skill specifies a name of a directory. The instance above will emanate a /dist/bundle.js file.

Although it’s not compulsory, it’s improved to use a path.resolve() method when we conclude a path property, as it ensures accurate module resolution (the comprehensive trail of a outlay is combined according to opposite manners in opposite environments, procedure fortitude solves this discrepancy). If we use path.resolve, we need to require a path Node module during a tip of a webpack.config.js file.

3. Add a loaders

To add a loaders, we need to conclude a module property. Below, we supplement a babel-loader that allows we to safely use a ECMAScript 6 features in your JS files:

const trail = require("path");

module.exports = {
  entry: "./src/script.js",
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: "babel-loader",
          options: { presets: ["env"] }
        }
      }
    ]
  }
};

The config might seem formidable though it’s only copy-pasted from Babel loader’s documentation. Most loaders come with possibly a readme record or some kind of documentation, so we can (almost) always know how to configure them properly. And, a Webpack docs also have a page that explains how to configure module.rules.

You can supplement as many loaders as we need, here’s a full list. Note that we also need to install any loader with npm to make them work. For a Babel loader, we need to implement a required Node packages with npm:

npm implement --save-dev babel-loader babel-core babel-preset-env webpack

If we have a demeanour during your package.json file, you’ll see that npm added 3 Babel-related packages to a devDependencies property, these will take caring of a ES6 compilation.

4. Add a plugins

To add a plugins, we need to mention a plugins property. Plus, we also have to require a plugins one by one, as they are outmost modules.

In a example, we supplement dual Webpack plugins: a HTML Webpack plugin and a Preload Webpack plugin. Webpack has a nice plugin ecosystem, we can crop a full list here.

To need a plugins as Node modules, create dual new constants: HtmlWebpackPlugin and PreloadWebpackPlugin and use a require() function.

const trail = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const PreloadWebpackPlugin = require("preload-webpack-plugin");

module.exports = {
  entry: "./src/script.js",
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: "babel-loader",
          options: { presets: ["env"] }
        }
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin(),
    new PreloadWebpackPlugin()
  ]
};

Just like in a box of loaders, we also have to install a Webpack plugins with npm. To implement a dual plugins in a example, run a following dual commands in your authority line:

npm implement html-webpack-plugin --save-dev
npm implement --save-dev preload-webpack-plugin

If we check your package.json record now, you’ll see that npm added a dual plugins to a devDependencies property.

Run Webpack

To create a dependency tree and output a bundle, run a following authority in a authority line:

webpack

It customarily takes one or dual minutes for Webpack to build a project. When finished, you’ll see a identical summary in your CLI:

Bundling with WebpackBundling with Webpack

If all went right Webpack created a dist folder in a base of your plan and placed a dual bundled files (bundle.js and index.html) inside it.

Github repo

If we wish to check out, download, or flare a whole project, have a demeanour during our Github repo.

Add Comment