Barebones Webpack: Module Bundling

We'll start by using webpack in it's simplest form: as a module bundler. One of Webpack's core features is it's ability to do CommonJS-style module requires. This means we can organize our front end code into separate files just like we'd organize a NodeJS project.

Webpack expects a configuration file to be present in the current directory called webpack.config.js. Create that file and paste in the following configuration:

var webpack = require('webpack');
var path = require('path');

module.exports = {
  context: __dirname,

  output: {
    path: path.join(__dirname, 'build'),
    filename: 'app.js'
  },

  entry: [
    './js/app.js'
  ]
}

This is the bare minimum amount of configuration that you need to make use of Webpack. Let's break down what this file is doing.

context - Sets the base directory webpack uses to resolve the entry option.

output - The file webpack should output the compiled javascript to.

entry - The "entry" files are the files webpack starts with to bundle your application.

Now, create two javascript files in the js folder, app.js and example:

// js/app.js
var Example = require('./example.js');

Example.hello();


// js/example.js
module.exports = {
  hello: function() {
    return "Hello, world!";
  }
}

Here we have two files, app.js, our "entry" file, and example.js, a file that is required in app.js.

Bundle the App

Now, let's bundle this app:

webpack -d --display-reasons --display-chunks --progress

A Note about module.exports for non-NodeJS Programmers

If you've programmed in NodeJS, module.exports is likely familiar to you, and you can safely skip this note.

module.exports is how you tell the module bundling system (in this case, webpack) what you want that file to "export", or, make available to a file that is requiring it. One of the goals of

results matching ""

    No results matching ""