Lesson Weekend

Remember that scripts field in our package.json? It's time to add our first script. Since we're using webpack to build our applications, we'll write a build script. Let's get rid of the test script for now (we'll add one later with Jasmine and Karma). The scripts section of our package.json file should look like this:

package.json
...

"scripts": {
    "build": "webpack"
  },
...

We can run any npm script with the $ npm run command. That means we can now type npm run build and webpack will try to build our project. However, as of now, if we type in npm run build, we'll get an error. Don't worry about resolving this error now.

Configuring Webpack

First, we need to set up a configuration file for webpack. This file should go in the top level of your project directory (on the same level as package.json). In order for webpack to find this configuration file, it must be named webpack.config.js. Let's create it now:

webpack.config.js
const path = require('path');

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

This is a very basic configuration. Let's go over the main points:

  1. Anything webpack requires to run goes at the top of our configuration file. For now, we only have require('path'), which we add to configure the path where our output files will be saved. We save this in a const variable. We'll soon be adding more require statements.

  2. We specify an entry point. This is the JS file where webpack will enter our application and then use a dependency graph to load all other required JS files.

  3. We also specify an output. This is where all our code will go after it's processed. webpack will automatically concatenate our JS files for us and then save them in a file called bundle.js in a folder called dist. We only have access to path because we required it at the top of our configuration file.

  4. All of our configuration is stored inside of module.exports. This is a Node.js convention. Essentially what we are doing is putting our configuration inside of a module and making it available for exporting. This means that other files will be able to import this module.

Now that we have a very basic configuration file in place, we're almost ready to process and concatenate some JavaScript code. We will still get an error message if we try to build our project. However, we need to learn about import and export statements before we resolve this error.