导读:React作为近年来大红大紫的view层框架,以其高效、灵活性、强大的社区环境而受到广泛关注。但React也不是直接就能拿来使用的,它必须通过配置相应环境才能更好的开发项目。虽然你可以使用官方推荐的构建React环境方式Create React App ,但有时候也想知道到底它是怎么配置的,所以自己动手搭建React环境也是很必要的学习过程。本系列分为5章,翻译自codecademy关于React搭建的教程。本篇原文地址:React Setup, Part II: Babel。
Background
Before React code can run in the browser, it must be changed in certain ways. One necessary transformation is compiling JSX into vanilla JavaScript.
React代码要想在浏览器运行,必须以某种方式进行转变。一种必要的转变是将JSX编译为普通的JavaScript。
Install Babel
Babel is a JavaScript compiler that includes the ability to compile JSX into regular JavaScript. Babel can also do many other powerful things. It’s worth exploring outside of the context of this course!
Babel是一个JavaScript编译器,它具备将JSX编译为正规JavaScript语言的能力。当然Babel还可以做其他强大的事情。它在课下也很值得探索。
Babel’s npm module’s name is babel-core
. You’re going to install babel-core
slightly differently than you installed react
and react-dom
. Instead of npm install --save babel-core
, you will use the command npm install --save-dev babel-core
.
Babel的npm包的名字叫做babel-core
。安装babel-core
的方式同安装react
和react-dom
的方式有所差别。你需要用npm install --save-dev babel-core
,而不是npm install --save babel-core
。
This is because you will only be using Babel in development mode. When a React app is shipped into production, it no longer needs to make transformations: the transformations will be hard-coded in place. The --save-dev
flag saves an npm module for development version only.
这是因为你只是在开发模式下用到Babel。当React app进入到产品阶段时就没必要做转变了:转变已经被硬编码到位了。--save-dev
标记只会保存npm模块的开发版本。
Just as --save
can be shortened to -S
, --save-dev
can be shortened to -D
.
就像--save
可以被简写为-S
一样,--save-dev
也可以被简写为-D
。
You’re also going to install two other babel-related modules, named babel-loader
and babel-preset-react
, respectively. We’ll explain those soon!
你接下来需要安装另外两个与babel相关的模块,叫做babel-loader
和 babel-preset-react
。我们稍后将做出解释。
Use one of these terminal commands to install babel-core
, babel-loader
, and babel-preset-react
:
用下面任意一个终端命令来安装babel-core
、 babel-loader
和babel-preset-react
。
Configure Babel
In order to make Babel work, you need to write a babel configuration file.
为了使Babel工作,你需要编写一个配置文件。
In your root directory, create a new file named .babelrc
. If you get prompted about starting a filename with a period, go ahead and say that it’s okay.
在你的(项目的)根目录下创建一个叫做.babelrc
的新文件。如果你收到有关创建以.开头的文件名的提示,继续,没事的。(译者注:在windows下可以命名文件为.babelrc.
来创建该文件,前后有两个点号,以避免windows弹出“必须键入文件名”的警告)
Save the following code inside of .babelrc
:
在.babelrc
中保存以下代码:
That’s it! Babel is now ready to go.
Whenever you’re ready, continue to our next article!
好了,Babel现在已经配置好了。
当你准备好了,那就开始下一篇文章吧!