BabelJS - Working with Babel and JSX



In this chapter, we will understand working with JSX and babel. Before we get into the details, let us understand what JSX is.

What is JSX?

JSX is a JavaScript code with a combination of xml syntax in it. JSX tag has tag name, attributes and children which make it look like xml.

React uses JSX for templating instead of regular JavaScript. It is not necessary to use it, however, following are some pros that come with it.

  • It is faster because it performs optimization while compiling code to JavaScript.

  • It is also type-safe and most of the errors can be caught during compilation.

  • It makes it easier and faster to write templates, if you are familiar with HTML.

We have used babel 6 in the project setup. In case you want to switch to babel 7, install the required packages of babel using @babel/babel-package-name.

We will create project setup and use webpack to compile jsx with react to normal JavaScript using Babel.

To start the project setup, run the commands given below for babel, react and webpack installation.

command

npm init

Webpack Installation

Now, we will install the necessary packages we need to work with – babel ,webpack and jsx −

npm install --save-dev webpack
npm install --save-dev webpack-cli
npm install --save-dev webpack-dev-server
npm install --save-dev babel-core
npm install --save-dev babel-loader
npm install --save-dev babel-preset-es2015
npm install --save-dev babel-preset-react
npm install --save-dev react
npm install --save-dev react-dom

Here is the package.json after installation −

Work_With_Babel_Webpack

Now will create a webpack.config.js file, which will have all the details to bundle the js files and compile it into es5 using babel.

To run webpack using server, there is something called webpack-server. We have added command called publish; this command will start the webpack-dev-server and will update the path where the final files are stored. Right now the path that we are going to use to update the final files is the /dev folder.

To use webpack we need to run the following command −

npm run publish

We will create the webpack.config.js files, which have the configuration details for webpack to work.

The details in the file are as follows −

var path = require('path');

module.exports = {
   entry: {
      app: './src/main.js'
   },
   output: {
      path: path.resolve(__dirname, 'dev'),
      filename: 'main_bundle.js'
   },
   mode:'development',
   module: {
      rules: [
         {
            test:/\.(js|jsx)$/,
            include: path.resolve(__dirname, 'src'),
            loader: 'babel-loader',
            query: {
               presets: ['es2015','react']
            }
         }
      ]
   }
};

The structure of the file is as shown above. It starts with the path, which gives the current path details.

var path = require('path'); //gives the current path

Next is the module.exports object, which has properties entry, output and module.

Entry is the start point. Here we need to give the main js files we want to compile.

entry: {
   app: './src/main.js'
},

path.resolve(_dirname, ‘src/main.js’) -- will look for the src folder in the directory and main.js in that folder.

Output

output: {
   path: path.resolve(__dirname, 'dev'),
   filename: 'main_bundle.js'
},

Output is an object with path and filename details. Path will hold the folder in which the compiled file will be kept and filename will tell the name of the final file to be used in your .html file.

module

module: {
   rules: [
      {
         test:/\.(js|jsx)$/,
         include: path.resolve(__dirname, 'src'),
         loader: 'babel-loader',
         query: {
            presets: ['es2015','react']
         }
      }
   ]
}
  • Module is object with rules details which has properties ie test, include , loader, query.

  • Test will hold details of all the js file ending with .js and .jsx.It has the pattern which will look for .js and .jsx at the end in the entry point given.

  • Include tells the folder to be used for looking the files.

  • Loader uses babel-loader for compiling code.

  • Query has property presets, which is array with value env – es5 or es6 or es7. We have used es2015 and react as the preset.

Create folder src/. Add main.js and App.jsx in it.

App.jsx

import React from 'react';

class App extends React.Component {
   render() {
         var style = {
         color: 'red',
         fontSize: 50
      };
      return (
         <div style={style}>
            Hello World!!!
         </div>
      );
   }
}
export default App;

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(, document.getElementById('app'));

Run the following command to bundle the .js file and convert it using presets es2015 and react.

command

npm run pack

Convert_Using_Presets

Add main_bundle.js from the dev folder to index.html

<!DOCTYPE html>
<html lang = "en">
   <head>
      <meta charset = "UTF-8">
      <title>React App</title>
   </head>
   <body>
      <div id = "app"></div>
      <script src = "dev/main_bundle.js"></script>
   </body>
</html>

command

npm run publish

Dev Folder To Index

Output

Dev Folder To Index Output
Advertisements