自己動手搭建React開發環境之二Babel

導讀: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的方式同安裝reactreact-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-loaderbabel-preset-react。我們稍後將做出解釋。

Use one of these terminal commands to install babel-core, babel-loader, and babel-preset-react:

用下面任意一個終端命令來安裝babel-corebabel-loaderbabel-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現在已經配置好了。
當你準備好了,那就開始下一篇文章吧!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章