Skip to content
Thai Pangsakulyanont edited this page May 23, 2016 · 24 revisions

INSTALLATION

You can install webpack via npm:

npm install webpack -g

Note: We’re installing webpack globally for demonstration purposes. When you are building a real application, it’s more advisable to install webpack as a devDependency of your project.

GETTING STARTED

First, we’ll learn the basics of webpack by using just webpack’s command-line interface.

Create a modular JavaScript project

Let’s create some modules in JavaScript, using the CommonJs syntax:

cats.js

var cats = ['dave', 'henry', 'martha'];
module.exports = cats;

app.js (Entry Point)

cats = require('./cats.js');
console.log(cats);

The “entry point” is where your application will start, and where webpack will start tracking dependencies between modules.

webpack in 5 seconds

Give webpack the entry point (app.js) and specify an output file (app.bundle.js):

webpack ./app.js app.bundle.js

webpack will read and analyze the entry point and its dependencies (including transitive dependencies). Then it will bundle them all into app.bundle.js.

Now your bundle is ready to be run. Run node app.bundle.js and marvel in your abundance of cats.

node app.bundle.js
["dave", "henry", "martha"]

You can also use the bundle in the browser.

GETTING SERIOUS

webpack is a very flexible module bundler. It offers a lot of advanced features, but not all features are exposed via the command-line interface. To gain full access to webpack’s flexibility, we need to create a “configuration file.”

Project structure

In real-world webpack projects, we’ll separate the source files from the bundled files by organizing them in folders. For this example, we’ll put the source files in src, and bundled files in bin.

Our final project structure will look like this:

In the wild, there are many project structures. Some projects use app instead of src. Some projects use dist or build instead of bin. Projects with test usually use test, tests, spec, specs or colocate the test files in the source folder.

  1. Create the bin and src directory.

    mkdir bin
    mkdir src
    
  2. Move the original source files to the src folder.

    mv app.js cats.js src
    
  3. Initialize an npm project.

    npm init # (answer the questions)
    
  4. Install webpack as a development dependency. This lets your project declare the version of webpack it is compatible with.

    npm install --save-dev webpack
    

Creating a webpack configuration file

Create a webpack.config.js file:

module.exports = {
    entry: './src/app.js',
    output: {
        path: './bin',
        filename: 'app.bundle.js'
    }
};

Running webpack

This time, just run:

webpack

In this case, webpack will read the configuration from webpack.config.js, so no need to specify the entry point this time.

It will build the bundle, and save it as bin/app.bundle.js. If you examine webpack's output you'll see that it included both source files. Run bin/app.bundle.js and you'll get your list of cats again.

node bin/app.bundle.js
["dave", "henry", "martha"]

You can also require() modules installed via npm with no extra configuration.

Using loaders

Most people will be using a transpiler for ES6, CoffeScript, TypeScript, etc. We're going to tell webpack to run our source files through babel so we can use React and JSX. We'll do this by specifying a loader for JS(X) files. Webpack will use the loader to parse the files before including them in the bundle. To add babel as a loader, you add the the module/loader section to your webpack.config.js file:

const webpack = require('webpack');

module.exports = {
	entry: './src/app.js',
	output: {
		path: './bin',
		filename: 'app.bundle.js',
	},
	module: {
		loaders: [{
			test: /\.jsx?$/,
			exclude: /node_modules/,
			loader: 'babel',
        }]
	}
}

You'll need to include babel-core and babel-loader as dev dependencies (For an actual project you'll need to include the supporting babel plugins as well, like babel-preset-es2015):

npm i --save-dev babel-core babel-loader

There are a number of different loaders you can use to include files in your app bundle, including css and image loaders.

Using plugins

Usually you'll want to do some additional processing of the bundle in your workflow. An example would be minifying your file so that clients can load it faster. This can be done with plugins. We'll add the uglify plugin to our configuration:

const webpack = require('webpack');

module.exports = {
	entry: './src/app.js',
	output: {
		path: './bin',
		filename: 'app.bundle.js',
	},
	module: {
		loaders: [{
			test: /\.jsx?$/,
			exclude: /node_modules/,
			loader: 'babel',
		}]
	},
	plugins: [
		new webpack.optimize.UglifyJsPlugin({
			compress: {
				warnings: false,
			},
			output: {
				comments: false,
			},
		}),
	]
}

The Uglify plugin is included with webpack so you don't need to add additional modules, but this may not always be the case. You can write your own custom plugins. For this build, the uglify plugin cut the bundle size from 1618 bytes to 308 bytes.

FURTHER READING

Recommended reading: Webpack your bags by Maxime Fabre - a very good introduction on how to setup a real-world project using Webpack.

Clone this wiki locally