Setting an ES6 Development environment with Node, Babel and Webpack

Setting an ES6 Development environment with Node, Babel and Webpack

Learn how to set up a dev environment for ES6 with Node, Webpack and babel and get to discover what are these tools and how to use them with details.

·

6 min read

  • ES6 is a standard Javascript version that's used by the majority of the tech communities working with Javascript. Many libraries and big tech solutions are built with ES6.
  • The issue is that the code of ES6 isn't understandable by the browser, because the browsers understand the earlier versions of Javascript (ES5 is the latest JS version that all browsers understand without the need to convert). Thus, we need to convert ES6 code to ES5, if we want our web applications written in Javascript to run correctly on web browsers.

To create a devlopment environment for ES6 we need a set of tools:

  • Node (runtime environment).
  • Babel (transpiler).
  • Webpack (module bundler).

Node

  • Node is a JavaScript runtime environment that runs on the V8 engine.
  • Node allows us to run JS code on our machine without the need for a web browser.
  • To install Node, I prefer using NVM (Node Version Manager). You can find the installation instructions in here.
  • If you have Node installed on your machine, you can skip this step.

Babel

  • A transpiler aka a source-to-source translator or transcompiler takes a source code written in a programming language as produces its equivalent source code in another programming language.
  • In Javascript, Babel is the most used transpiler and it is an industry standard.
  • Babel will convert the ES6 code to pre-ES6 code that the browser can understand and execute.

Webpack

  • A module bundler parcels or bundles different modules or code files into generally one file (sometimes more than one, according to the developer's need and preference).
  • Webpack is an open-source JS module bundler.
  • It takes modules with dependencies and generates static assets representing those modules.
  • It helps us reduce the time spent on loading resources.

Practice

Setting up Wepback (linux users)

  • Open your terminal and execute the following commands.
    mkdir tutorial
    cd tutorial
    npm init -y
    
  • The npm init -y command allows us to make the basic setup for our JS project configuration and it'll show us the content of the packge.json file, which is:
    {
    "name": "tutorial",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC"
    }
    
  • Now we're going to install webpack as a development dependency with the --save-dev option. It's because we only need webpack for the development cycle of our project and now for the execution of it on the browser (if it was a CSS library or a library that the user needs when the app is running on the browser, we install it as a dependency otherwise as a dev dependency).
    npm install webpack webpack-cli --save-dev
    
  • Now our package.json file will look like this:
    {
    "name": "tutorial",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
      "webpack": "^5.38.1",
      "webpack-cli": "^4.7.0"
    }
    }
    
  • Create a folder to put our code.
    mkdir src
    cd src
    touch index.js
    
  • For the rest of the project modify the files with your preferred code editor or IDE. There's a variety of editors that you can choose from i.e VSCode, Atom, SublimeText, emacs, vim...
  • Inside the index.js, add the following code
    console.log("Hello World");
    
  • Configure webpack to bundle our code from the index.js file. inside the package.json, the start script is for the development cycle of the app and the build is for the production version.
    "scripts": {
    "start": "webpack --mode development",
    "build": "webpack --mode production"
    }
    
  • Let's run the start command and see what's gonna happen
    npm run start
    
  • It generated a dist folder with a main.js file that contains JS code. the main.js file is genereted by webpack
  • So far webpack behaves according to its default configuration. Now let's define our own webpack configuration. make sure you're exactly inside the tutorial folder then type:

    touch webpack.config.js
    
  • Inside the webpack.config.js file, add the following:

    const path = require('path'); // NodeJS module, to work with absolute paths.
    module.exports = {
    entry: path.resolve(__dirname, 'src'), // which folder to look at for JS files to bundle
    output : { // where to generated the bundled code
      path: path.resolve(__dirname, 'dist'), // folder
      filename: 'bundle.js' // file
    },
    };
    
  • When we run npm run start, a bundle.js file will be generated in the dist folder.
  • With the current config each time we change our javascript code we need to stop the run command and relaunch it again. This is very time and energy consuming, thus webpack comes with its own server that has hot reloading (it relaunches the npm run start command when we change and save our code).
  • Install webpack server
    npm install -D webpack-dev-server --save-dev
    
  • Change the start script to:
      "start": "webpack serve --mode development",
    
  • Update the webpack.config.js, by adding this to the exported module:
    devServer: {
      hot: true, // to reload the server after code update
      port: 5000, // port on which the server is running
      contentBase: path.resolve(__dirname, 'build') // the directory to serve from.
    },
    
  • In real projects, there's always an index.html file that calls the bundle.js file. Add an HTML file named index.html in the dist folder with the following content.
    <!DOCTYPE html>
    <html>
    <body>
      Hello from simple HTML
      <script src='bundle.js'></script>
    </body>
    </html>
    
  • When you run the npm run start then update and save your JS code the webpack will reload the server. you can view the page on localhost

  • Now we have to add Babel to our configuration to make the browser understand ES6 but first we have to install the following dev packages:

    npm i @babel/core babel-loader babel-preset-env --save-dev
    
  • babel-core: the primary transplier.
  • babel-loader: converts modern JS code into plain old JS code supported by browsers.
  • **babel-preset-env: a smart preset that allows you to use the latest JavaScript without needing to micromanage which syntax transforms (and optionally, browser polyfills) are needed by your target environment(s).

    • Adding the babel transpiler to the webpack configuration will be inside the "module" property that defines how modules are treated within webpack
      module: {
      rules: [ // an array of rules as objects
        { // configure babel on which files it should convert.
          test: /\.js$/, // to target all files that ends with '.js'
          exclude: /node_modules/, // exclude everything in the node_modules.
          use: ['babel-loader'] // the loaders used in this rule.
        }
      ]
      }
      
  • Add a .babelrc file in the tutorial folder. the file name starts with '.' because it's a hidden file and it's has 'rc' at the end to refer to it as a Runtime Command file, that executes while the loader is transpiling.
// content of .babelrc file
{
  "presets": [
    "env"
  ]
}
  • babel-presets are collections of plugins used to support particular language features. In other words, a preset is plugin that performs a particular transformation.

Conclusion

  • This is a simple configuration that you can build upon for more complex projects.
  • If you want to access to the whole config, you can find it on Github