Labels

javascript (9) css (3) babel (1) nodejs (1) webpack (1)

Friday, March 24, 2017

Webpack + Babel

The purpose of this post is not to make anyone an expert with Webpack or Babel but to simply demonstrate a very basic setup that uses Webpack for bundling your ES6, or ES2015, code using Babel. There is an associated Git repo you are free to clone and change however you like.

The first thing you want to do, as with most projects, is set up your environment:

npm init

This will ask you for some information so just fill it all out to get setup.

Then next thing you will want to do is install the required dependencies:

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

As you can see, this will install Webpack and the required Babel plugins and set them up as a dependency for your project in your package.json file.

From there, all we need to do is write some code!

Here is a very simple webpage that will display the name you set in JavaScript. Here is the complete source:

index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Webpack + Babel example</title>
    </head>
    <body>
        <h1 id="example"></h1>

        <script src="dist/bundle.js"></script>
    </body>
</html>
src/example.js
/**
 * This uses ES6 modules to export the Example class
 * which takes a value for name as a constructor argument.
 * It returns that name with the getName function.
 */
export default class Example {
    constructor(name = "Webpack") {
        this.name = name;
    }

    getName() {
        return this.name;
    }
}
index.js
// This imports the class Example from example.js
import Example from './src/example';

// Now using it is as simple as...
let example = new Example("Webpack + Babel"),
    h1Example = document.getElementById("example");

h1Example.innerText = example.getName();
webpack.config.js
let path = require('path');

// You can view the docs for Webpack but basically, entry is 
// the file to start with and output is where you want it to go.
// There is a lot more you can do with this.
module.exports = {
    entry: './index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    }
}

Once that is all done, you can simply type webpack at the command line and Webpack will find the webpack.config.js file at the current working location and then bundle your JavaScript. We have it set to go to the dist folder as bundle.js which will automatically be created (directory also) if it is not already there.

One thing you can also do is type:

webpack --watch --colors --progress

This will automatically run webpack any time there is a change to the code.

Now that you have a basic understanding on this Webpack + Babel thing, check out Webpack's guides to learn more. I hope this helps you in your future projects.

You can view the repository here in case you wanted to use it as a starting point.