Webpack with Babel 7 Project Setup

What is Webpack and Babel

If you have been working with Javascript for any period of time you have most likely worked with both of these pieces of technology. And in tandem, they have a great working relationship. Webpack is a module bundler used for taking your JavaScript code modules and bundling it all together. Also, if you’ve ever worked with React or Angular, and you have experienced the nice feature of Hot Module Replacement(HMR) where your code updates the browser, without necessarily needing to do a page refresh. To be honest, this was a game changer for me. No longer needing to hit the Ctrl + F5 is such a nice advancement!

Babel, on the other hand, is a transpiler. Babel (and I love their copy by the way) allows you to use next generation JavaScript, today! In other words, Babel will take the more modern features of the ECMAScript ecosystem and compile (or more appropriately transpile) them down to code that can run on older browsers, that don’t recognize all of the modern features of ES6.

As you can guess the two of these together can create a powerful tool, especially if you are not going to run straight to a framework or library like React which comes set up with it. So, I thought I would share a post with you on how to set up your own configuration and get you through the heavy lifting part of initial dependencies.

Initial Setup

You’ll need to have node installed on your machine, I prefer to use NVM, as I can switch between node versions, but more recent versions of node and npm will work. You can find the most recent version of node here.

Create a folder then run npm init. Following that you’ll need to save and install webpack and the webpack-cli to your project. Run the following command npm install --save-dev webpack webpack-cli. We also used the --save-dev flag as this is a development dependency in the project. Pretty much the rest of these dependencies are going to be saved as a development dependency.

Next you will need to modify the package.json file’s "scripts" property by adding "build": "webpack" to it, there should already be a "test": "echo \"Error: no test specified\" && exit 1", property. But make sure to add a comma following that test property. Note that some of these dependencies can change, so I am going to make a repository on my GitHub, which you can use to follow any updates to these commands.

There are 6 different plugins that are pretty standard with a Babel/Webpack setup, and I am going to give you the command to run. You can look up the individual plugins yourself, but understand that these are what allow our Webpack and Babel transpilation to integrate and play nice with each other. Inside your project run npm install --save-dev babel-loader @babel/core @babel/preset-env html-webpack-plugin script-ext-html-webpack-plugin. And one other npm install --save-dev @babel/register.

Configuration Files

We are going to need to separate configuration files for this setup to work. We need a Webpack config and a Babel config. The Webpack config does most of the heavy lifting, whereas the Babel config you see pretty much just tells which files to watch and where to transpile them out to. I use bash terminal so follow along if you can or just use your ide. touch webpack.config.babel.js, then vim webpack.config.babel.js. Enter then copy the following configuration over.

import path from 'path';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import ScriptExtHtmlWebpackPlugin from 'script-ext-html-webpack-plugin';
export default {
    entry: path.join(__dirname, 'src/index.js'),
    output: {
        path: path.join(__dirname, 'dist'),
        filename: '[name].bundle.js'
    },
    module: {
        rules: [{
            test: /\.js/,
            exclude: /(node_modules|bower_components)/,
            use: [{
                loader: 'babel-loader'
            }]
        }]
    },
    plugins: [
        new HtmlWebpackPlugin({
            title: 'Custom template',
            template: path.join(__dirname, 'src/index.template.html')
        }),
        new ScriptExtHtmlWebpackPlugin({
            defaultAttribute: 'defer'
        })
    ],
    stats: {
        colors: true
    },
    devtool: 'source-map'
};

This config basically looks for the entry of our javascript files provided and processes it through the modules. It uses plugins to make sure the HTML is processed as well.

Next, we need to create a much shorter Babel config file. touch .bablerc. The default file name processed by Babel 7 for defining the configuration during its transpilation process. Now test out using npm run build. If you’ve set up everything correctly up to this point you should not run into any errors. I had a few warnings

Run the Project with Live Server

This wouldn’t be complete if we didn’t take advantage of running our code on Webpack’s live server. npm install --save-dev webpack-dev-server then we need to modify our webpacl.config.babel.js file to include our dev server properties.

In your config add the following devServer property.

mode:"development",
    devServer: {
            contentBase: './dist',
            inline:true,
            port: 3000
    }

And in our package.json add the following to our script properties:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "watch": "webpack --watch",
    "start": "webpack-dev-server --open",
    "build": "webpack"
  },

Here is the entire package.json, in case you have any question about what versions of dependencies are used here.

{
  "name": "babel-webpack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "watch": "webpack --watch",
    "start": "webpack-dev-server --open",
    "build": "webpack"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.2.2",
    "@babel/preset-env": "^7.2.3",
    "@babel/register": "^7.0.0",
    "babel-loader": "^8.0.5",
    "html-webpack-plugin": "^3.2.0",
    "script-ext-html-webpack-plugin": "^2.1.3",
    "webpack": "^4.28.4",
    "webpack-cli": "^3.2.1",
    "webpack-dev-server": "^3.1.14"
  },
  "dependencies": {}
}

We are now ready to run our development server using the previously mentioned live reloading of our code using webpack’s Hot Module Replacement(HMR). Pretty sweet! Test it out. Use npm run start to fire up our development server and run our code live with HMR.

Thanks again for reading and I hope you found this useful, you can find the GitHub of the code here, so that if you want to forgo the setup yourself you can just clone and run. If you want to take advantage of JavaScripts newer features, you can take advantage of Babel and use them now. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *