官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 博湖县| 乐平市| 金门县| 兴山县| 隆子县| 上栗县| 焦作市| 龙陵县| 柳河县| 通山县| 河池市| 永寿县| 泾源县| 潞城市| 文安县| 宁安市| 宁国市| 宿迁市| 赤城县| 嘉义县| 卢氏县| 德化县| 九江市| 清涧县| 商南县| 屏东市| 仙桃市| 萍乡市| 金塔县| 个旧市| 巴中市| 临朐县| 汤原县| 奉新县| 阿勒泰市| 右玉县| 吉水县| 三门县| 高唐县| 清苑县| 蒙阴县|