Babel 7

To use JSX (and some features of ES6) in our code, we have to install the new Babel 7.

First of all, it is important to clearly understand the problems it can solve for us and why we need to add a step to our process. The reason is that we want to use features of the language that have not yet been added in the browser, our target environment. Those advanced features make our code cleaner for developers, but the browser cannot understand and execute it.

The solution is to write our scripts in JSX and ES6, and, when we are ready to ship, we compile the sources into ES5, the standard specification implemented in major browsers today.

Babel is a popular JavaScript compiler widely adopted within the React community.

Babel can compile ES6 code into ES5 JavaScript, as well as compile JSX into JavaScript functions. The process is called transpilation, because it compiles the source into a new source rather than into an executable.

In older versions of Babel 6.X, you installed the babel-cli package and you got babel-node and babel-core now everything is separated: @babel/core@babel/cli@babel/node, and so on.

To install it, we need to install @babel/core and @babel/node as follows:

  npm install -g @babel/core @babel/node

If you do not want to install it globally (developers usually tend to avoid this), you can install Babel locally to a project and run it through an npm script, but for this chapter, a global instance is fine.

When the installation is complete, we can run the following command to compile any JavaScript file:

  babel source.js -o output.js

One of the reasons Babel is so powerful is because it is highly configurable. Babel is just a tool to transpile a source file into an output file, but to apply some transformations, we need to configure it.

Luckily, there are some very useful presets of configurations that we can easily install and use:

  npm install -g @babel/preset-env @babel/preset-react

Once the installation is complete, we create a configuration file called .babelrc in the root folder, and put the following lines into it to tell Babel to use those presets:

  {
"presets": [
"@babel/preset-env",
"@babel/preset-react"
]
}

From this point on, we can write ES6 and JSX in our source files and execute the output files in the browser.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.111.183