Category: webpack

Babel and Webpack for compiling and bundling JavaScript ES6 (ES6/ ES7/ ES8)

In this article i am going to explain how to use the Babel compiler  for compiling the javascript from ES6(or higher ES version) to ES5 compliant version. In addition, the webpack will be used for  executing barbel compiler and bundling the multiple javascript dependencies into a single file.

The majority of the internet browsers are supported to run ES5 compliant JavaScript. Therefore if you develop your application with ES6 or any other latest ECMAScript version, you may need to compile or transform it into ES5 compliant version for running it in most of the available browsers.

 

What is Babel?

Babel is a JavaScript transpiler (or known as javascript compiler). Babel enables us to write modern JavaScript that will be “transpiled” to widely-supported ES5 JavaScript. We call this process as “transpiling”.

Want to know more about Babel? Click here 

 

Start the project with NPM 

NPM is stands for Node Package manager. As the name implies , it is the package manager for JavaScript. This is installed when you install the NodeJs in your development environment.  NPM contains a large number of reusable JavaScript packages and modules.

to check and verify the NPM installation in your development environment, you can run the following command in the terminal . It will display the NPM version if it is already installed.

npm -v

 

If you do not have npm installed in your machine, you can refer the official website (www.npmjs.com)  for getting the instructions for installing it.

So once the installation is verified, we can create the JavaScript project with NPM with following command. This will create a standard package.json file for the project.

npm init

 

Screen Shot 2018-01-27 at 6.52.03 PM.png

What is package.json file?

This is the file that contains the all important information about your project(package). it contains information about project name, version, author, license, main script, list of dependencies, how to build the project, how to start the project etc..

Please refer the official documentation for more information.

The generated package.json file for this project can be shown as below.

 

Here you can see that main script file is main.js . So we need to create it. In addition i have created two other JavaScript files and do some ES6 based javascript codings to demonstrate the beauty of the ES6 and Webpack bundler.

 

calculator.js

Here is the beauty of the ES6. we can have a class with both static and non-static methods.

 

welcome.js

returns the welcome message by concatenating the user given name.

 

main.js

 

window object represents the browser window. if any property (variable, function or class) is assigned to the window, then it can be accessed through the browser. That is why we have assigned the properties (class and methods) for the window object here.

 

index.html 

you can see that we have imported the main.js file here. That file contains the ES6 based javascript and that is not compiled down to ES5.

when you loading the page on browser, you might get following error in the browser console.

main.js  Uncaught SyntaxError: Unexpected token export

 

This means that your browser is not supported for ES6  and it cannot understand the syntaxes written in ES6 style. Therefore we need to transform the ES6 style code into browser understandable ES5 style code. In this situation, Babel comes to play role of traspiling the source code.

 

Setting up Babel 

We need to install following few dependencies for getting the babel compiler for the project.

  • babel-core :- includes the babel core modules
  • babel-loader  :-  loader for running the ES6+ and JSX with webpack. This will be configured in the webpack.config.js
  • babel-preset-env :- (or any other preferred preset). The preset will also be configured in the webpack.config.js or can be defined in .babelrc file
  • babel-polyfill :- A polyfill is a piece of code, that replicate the fully ES6+ environment into the targeted runtime environment. Therefore some of the transpiled ES6+ based methods and objects can be executed in ES5 environment without any runtime error.  If you want to learn more about babel-polyfill, please click here to go to my article on that.

 

Here is a good article to learn more about babel.

https://kleopetrov.me/2016/03/18/everything-about-babel/

 

What is the purpose of barbel preset?

presets are plugins that enable the features and support for particular language. for example, If the JavaScript code is based on ES6, we need to tell the babel transpiler that the source code is based on ES2015. So it will enables the required features for transforming the ES6 code to ES5.  if the source codes is based on reactjs, we need to enable the react preset.

For more information about “preset”, please visit the official website.

https://www.npmjs.com/package/babel-preset-env

https://babeljs.io/docs/plugins/#presets 

 

Why do we enable “babel-preset-env” without enabling “babel-preset-es2015” ?

This is a good point. This preset will automatically detect the ECMAScript version of your source code and enable the related features for compiling the source code into ES5 version.

babel-preset-env is the latest babel preset that compiles ES2015+ (ES6, ES7, ES8 ) down to ES5 by automatically determining the Babel plugins needed based on your targeted browser or runtime environments.

Without any configuration options, babel-preset-env behaves exactly the same as babel-preset-latest (or babel-preset-es2015, babel-preset-es2016, and babel-preset-es2017 together).

In our case, we are trying to compile the ES6 code into ES5. So here babel-preset-env can be used.

We will install all the required dependencies for the babel with following command. This command should be run in your project directory.

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

 

–save :-

This will install the given dependencies in the project locally. that means the dependencies are installed in the node_modules directory that is located inside your project directory.

If you want to install it in globally, use -g flag. Then the dependencies will be installed in the /usr/local/lib/node_modules directory as global dependencies. 

 

–save-dev :-

install the dependencies locally as dev dependencies. If you open the package.json, you can notice that the installed dependencies have been categorized under devDependencies. The dev dependencies are used only for development purpose and those should be omitted when the package is released for the production. Otherwise the final distributed package will contains overhead/unnecessary dependencies that are not required in runtime (production environment).  dependencies will be included in the final distribution and devDependencies will be neglected.

Please refer the following snapshot of package.json.

"devDependencies": {
  "babel-loader": "^7.1.2",
  "babel-core": "^6.26.0",
  "babel-preset-env": "^1.6.1"
}

 

 

Setting up Webpack

Here i am assumed that you have the basic knowledge and understanding about webpack. If you don’t have, please go and refresh your knowledge about webpack.

I have found that below articles are useful for beginners who want to learn webpack.

https://tutorialzine.com/2017/04/learn-webpack-in-15-minutes

https://blog.andrewray.me/webpack-when-to-use-and-why/

 

So we will be moving forward with setting up webpack. First we need to install the webpack dependencies for the project and there are two dependencies required.

  • webpack
  • webpack-dev-server

These dependencies can be installed with following command.

npm install webpack webpack-dev-server --save-dev

 

After installing the webpack dependencies, the devDependencies of the package.json should looks like below.

"devDependencies": {
  "babel-core": "^6.26.0",
  "babel-loader": "^7.1.2",
  "babel-preset-env": "^1.6.1",
  "webpack": "^3.10.0",
  "webpack-dev-server": "^2.11.1"
}

 

So once the dependencies are installed, we need to create a webpack.config.js file and do the necessary configuration for the webpack.

 

Adding webpack.config.js

Add the webpack.config.js file in the root of your project. The sample configuration for the webpack.config.js can be given as follows.

With Webpack, running your JavaScript and JSX through Babel is a simple as adding the babel-loader to your webpack.config.js.

 

webpack.config.js

 

Here are the important things to note from the webpack.config.js

  •  The entry point of the app has been named as app.js
  •  The output file will be app.bundle.js and it will be stored in the build directory.
  •  babel-loader has been added as a loader for handling  .js and .jsx file (match of the regular expression)
  • node_modules directory will be excluded by the babel-loader when webpack is running.
  • babel-preset-env  (presets: [env])  has been added in the webpack configuration. Therefore .babelrc  file is not required for this setup.

 

Hint:
You can commit the  preset configuration in the webpack.config.js and 
replace it with .babelrc file.

 

Adding the build command for package.json

In the package.json we need to specify the build command as “build” “webpack” under the “scripts“.

"scripts": {
  "build": "webpack -p",
  "test": "echo \"Error: no test specified\" && exit 1"
},

 

weback  -p  :- run the webpack in production mode. this will minify the javascript code in the output file.  If you do not use the -p option, then your generated file will not be minified.

This is the finally modified  package.json file of our application.

 

All the related project files and configuration files has been created. So finally, our project structure should looks like below.

Screen Shot 2018-01-28 at 10.05.23 PM.png

 

Building the project with webpack

Now it is the time to build out project with webpack.  So we need to make sure that our javascript files that are in ES6 syntaxes are transform into ES5 with babel (with babel-loader) and  set of javascript dependencies are bundled as one single file (the purpose of webpack). We can run the following command in the command line.

npm run build

 

when you run the build command, it will execute the command given in the package.json under the build script.

"scripts": {
  "build": "webpack -p"
}

 

Since we have used webpack -p , the webpack will be ruin in the production mode.  the output file will contain the minified version of the javascript source file.

 

You can refer the following screenshot for further understanding.

Screen Shot 2018-01-28 at 10.07.41 PM.png

The related javascript source files are compiled and bundled into the build/app.bundle.js  file . You can use that build file in your HTML to import the javascript methods and functionalities.

 

This is the final project structure (after executing the webpack build) and i have given it for your further understanding.

Screen Shot 2018-01-28 at 10.19.05 PM.png

 

Test the app.bundle.js with index.html file 

 

Now we can add the app.bundle.js for the index.html file as a script and run it on browser.

 

Run on browser will give you the following output.  That means our ES6+ syntaxes are compiled down to ES5 and working as we expected.

 

Screen Shot 2018-01-30 at 1.33.05 PM.png

 

You can see that the console.logs are printed as we expected and the result is published to browser. You can play with chrome console to check whether the classes and methods has been assigned/attached to the window. (If you observe the Chrome console output in the screenshot, you can see that i have done it)

 

How to get the Source Code and Run it?

Now we have come to the end of the article.  The source code of this article can be found at GitHub.

click here to download the source code. 

 

Steps by Step guide for building and running the project

Get the source files from the GitHub.

git clone git@github.com:chathurangat/webpack-barbel-for-es6.git

 

Go inside the project directory.

cd webpack-barbel-for-es6

 

Install the dependencies for the first time (locally).

npm install --save

 

Run the webpack build task.

npm run build

 

If you have any further inquiry related to this article, please feel free to contact me.

Thanks

Chathuranga Tennakoon

 

NodeJS Simple Application with ECMAScript6 (Webpack + Babel + ES6)

 

In this article, i am going to develop simple NodeJs application that uses following technologies.

  • ES6 (ECMAScript6) based JavaScript Syntaxes
  • Babel for transpiling/compiling ES6 syntaxes into ES5.
  • Webpack for executing babel transpiler and bundling JavaScript  files into a single file
  • ExpressJs as the web application framework for NodeJs

Lets move forward to build our NodeJs application with ExpressJS using ES6+ JavaScript syntaxes.

 

Initializing the project and creating the package.json file.

NodeJs project should be a NPM based (managed) project. That means the dependent packages of the project should be managed with NPM. This can be achieved by creating the package.json file for the project.

The following command can be used to  create the package.json file with required intial configurations.

npm init

Once the npm init command is executed, you need to provide the project related details for the package.json. Please refer the below screenshot.

 

Screen Shot 2018-02-20 at 12.52.40 PM.png

 

Now the package.json is created and we can start the development of our NodeJs application.

 

Creating the project directory structure

The final project structure should looks like below.  Don’t worry at the moment. we will add each of files while we are moving forward with the article.

Screen Shot 2018-02-21 at 5.23.01 PM.png

 

Adding the external libraries and dependencies for the project.

As i have already pointed out, our NodeJs application depends on few external dependencies and  they can be listed as below.

  • Express.js
  • Babel
  • Webpack

We will move forward on installing each of these dependencies.

 

Installing Express.js dependency

Express.js is a web application framework for NodeJs. It has set of utility methods that simplifies the development of  the NodeJs applications.  Express.js is not bundled with NodeJs installation and we need to install it separately. It can be done with following command.

npm install express --save

After executing above command, you can see that ExpressJs  has been added to the dependencies list of the package.json file.

 

Installing Babel dependencies

Babel is used to transpile ES6+ based source code into ES5. This should be installed as a development related dependency as the transpiling is happened in the development environment. The following command will install the babel related dependencies in the development environment.

npm install --save-dev babel-core babel-loader babel-preset-env babel-polyfill
  • babel-core :- includes the babel core modules
  • babel-loader  :-  loader for running the ES6+ and JSX with webpack. This will be configured in the webpack.config.js
  • babel-preset-env :- (or any other preferred preset). The preset will also be configured in the webpack.config.js or can be defined in .babelrc file
  • babel-polyfill :- A polyfill is a piece of code, that replicate the fully ES6+ environment into the targeted runtime environment. Therefore some of the transpiled ES6+ based methods and objects can be executed in ES5 environment without any runtime error.  If you want to learn more about babel-polyfill, please click here to go to my article on that.

If you want to learn more about babel or webpack, please click here to visit article i have written on babel with Webpack.

Once the above command is executed successfully, you can see that the babel dependencies are installed under the devDependencies of the package.json

 

Installing the webpack dependencies

So we will be moving forward with setting up webpack. First we need to install the webpack dependencies for the project and there are two dependencies required.

  • webpack
  • webpack-dev-server

These dependencies can be installed with following command.

npm install webpack webpack-dev-server --save-dev

 

So once the dependencies are installed, we need to create a webpack.config.js file and do the necessary configuration for the webpack.

 

–save  : This will create a dependency entry under the dependencies of the package.json

–save-dev  : This will create a dependency entry under the devDependencies of the package.json

 

Once all the required dependencies are installed, the package.json of the project should looks like below. (This is just a sample snapshot of package.json and the versions of the dependencies can be different)

"dependencies": {
  "babel-polyfill": "^6.26.0",
  "express": "^4.16.2"
},
"devDependencies": {
  "babel-core": "^6.26.0",
  "babel-loader": "^7.1.2",
  "babel-preset-env": "^1.6.1",
  "webpack": "^3.11.0",
  "webpack-dev-server": "^2.11.1"
}

 

Lets look at each source file in detailed.

 

index.js 

create an index.js file in the root of your project.  The file should contains the following source. 

This is the entry point of your NodeJs application. This contains the application logic for spinning up the web server and handling the application routes (HTTP Routes)

This will create a web server and listen for the port 2000.  All the requests comes to the web server will be handled by the routes module developed in this application. we go through the routes module of the application in a while.

As you can see that we are using the ES6 based import here instead of ES5 based require. If you observe most of the source code in this project, you will notice that we have used ES6+ based syntaxes most of the places.

 

RequestHandlerService.js

This class hans been added demonstrate the robust features of ES6+ (Just to show the beauty of ES6+). This class will contain a simple method of handling HTTP request.

This method has been annotated with async. Therefore it guarantees that the method will return a promise.

 

routes.js

This file will contains the all the HTTP Route handlers related to this project. I am not going to explain all the route handlers here. I will just describe few of them for your understanding.

 

Lets look at some of the selected routes in detailed.  If you want to learn more about ExpressJS routing, it is recommended to read http://expressjs.com/en/guide/routing.html

router.all('/*', function (request, response, next) {
    console.log(" this will be applied to all routes ");
    next();
});

 

There is a special routing method, app.all(), used to load middleware functions at a path for all HTTP request methods. For example, the above handler is executed for requests to the route “/*” (for any route) with HTTP GET, POST, PUT, DELETE, or any other HTTP request method supported.

next() will delegate the request to the next available middleware or route.

 

router.get("/", async (request, response)=> {
    
    let message = await RequestHandlerService.handleHttpRequest(request.method, request.path);

    response.status(200).json({
        "message": message
    });
});

 

handleHttpRequest (Async method)  of the RequestHandlerService has been invoked in this route handler. Since the route handler function(arrow function) is modified with async keyword,it is possible to use the await keyword to wait for the result from the method invocation.

If you observe the last line of the file, you can see that we have export the module router. So the outside script can use this module.

module.exports = router;

 

webpack.config.js

Add the webpack.config.js file in the root of your project.The webpack.config.js related to this project can be shown as follows.

Using webpack, running/traspiling your JavaScript and JSX through Babel is a simple as adding the babel-loader to your webpack.config.js. It has been added as a loader and it will go through all js and JSX files. It uses the babel-preset-env as defined and excludes the files in the node_modules directory.

babel-polyfill will be added and managed by the webpack. In addition, index.js has been designated as a entry point js file for the project.

The output file will be stored in the build directory using file app.bundles.js.

 

Testing and Running the application.

Now we have come to the final section of our article. Here we will run the nodeJs application and test each application route.  In oder to run the application , we need to transpile the ES6+ syntaxes of the project into the ES5.

 

Transpiling/Compiling ES6+ syntaxes into ES5 with Babel and Webpack

Now we need to transpile/convert the ES6+ based source code into ES5 based source. This can be done with babel. In this project we use webpack to execute babel using babel-loader for the source code transpiling.  In oder to achieve this, go to the root of the project where your webpack.config.js is located.  Then run the following command to build the project.

webpack

 

Running the NodeJs application

Then you can see that project is build and final file is created in build/app.bundle.js. This is the file that should be run with node.

node build/app.bundle.js

 

Once the above command is executed, it will create a web server and up the NodeJs project. please refer the below screenshot.

Screen Shot 2018-02-21 at 5.01.31 PM.png

You can see that server is up and application listen on port 2000 for incoming  HTTP requests.

 

Executing both transpiling and running commands with NPM

We can combine both commands together and add a new command under the scripts of the package.json

"execute": "webpack && node build/app.bundle.js"

 

Now you can run following command to build and run the project. It will first build the project with webpack and then run the build file with node.

npm run execute

 

 

Now lets access each HTTP route with postman as follows. 

 

GET   http://localhost:2000/

Screen Shot 2018-02-21 at 7.30.27 PM.png

 

GET   http://localhost:2000/products/12

Screen Shot 2018-02-21 at 7.31.26 PM.png

 

POST    http://localhost:2000/products

Screen Shot 2018-02-21 at 7.32.30 PM.png

 

The source code of this article can be found in GitHub. Click here to get the source code. 

 

How to set up the project clone from GitHub

The source code has been added without the node_modules directory. Therefore run the following command to install the required dependencies for the project. This will install the dependencies locally for your project.

npm install

 

After that you can run project with following command.

npm run execute

 

This is the end of the article. If you have any concern or need any help, feel free to contact me.