Thursday, May 21, 2020

Bable

Babel is a JavaScript compiler which is used to transform ES6 JavaScript code to ES5 JavaScript which the browsers can understand. This transformation is called transpilation. React components are generally written using ES6 classes and JSX syntax, bable loaders are used to transpile ES6 and JSX code to core ES5 JavaScript.

Webpack cannot compile ES6 JavaScript code, hence it used loaders to transpile ES6 and JSX code. In the React sample we used bable-loader in the webpack configuration to compile ES6 and JSX code into native JavaScript code.

For the React Application we used the following 3 bable packages

      @babel/core - Core Bable package
      @babel/preset-env – Used to compile ES6 code to ES5
      @babel/preset-react – Used to compile JSX into native JavaScript

Apart from transpiration, bable can also include polyfills to support features which the target environment does not provide by default.  Some old browsers might not have support for modern JavaScript features, in which case we can include polyfills to make the old browsers compatible.

Bable configuration
Bable needs a configuration file .babelrc which contains an array of presets and plugins which the bable loader supports. The bable configuration file looks like this.
{
  "presets": [ <array of presets> ],
  "plugins": [ <array of plugins> ]
}

In our React sample we need 2 presets preset-env & preset-react to support ES6 and JSX transpilation, hence the .bablerc file for our React application looks like this.
{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ]
}

Finally once all the bable configuration is done we need to tell webpack to use the bable loader, this is done by specifying bable-loader in the .webpack.config.js file as follows.

  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader']
      }
    ]
  }


Search Flipkart Products:
Flipkart.com

No comments: