巴别塔圣经
Introduction to Babel
通天塔简介
Installing Babel
安装Babel
An example Babel configuration
Babel配置示例
Babel presets
Babel预设
env
preset
env
预设
react
preset
react
预设
More info on presets
有关预设的更多信息
Babel presets
Babel预设
Using Babel with webpack
将Babel与Webpack一起使用
This article covers Babel 7, the current stable release
本文介绍了Babel 7(当前稳定的发行版)
通天塔简介 (Introduction to Babel)
Babel is an awesome tool, and it’s been around for quite some time, but nowadays almost every JavaScript developer relies on it, and this will continue, because Babel is now indispensable and has solved a big problem for everyone.
Babel是一个了不起的工具,已经存在了很长一段时间,但是如今,几乎每个JavaScript开发人员都依赖它,而且这种情况还将继续,因为Babel现在已不可或缺,并且已经解决了每个人的大难题。
Which problem?
哪个问题?
The problem that every Web Developer has surely had: a feature of JavaScript is available in the latest release of a browser, but not in the older versions. Or maybe Chrome or Firefox implement it, but Safari iOS and Edge do not.
每个Web开发人员肯定都会遇到的问题:JavaScript的功能在最新版本的浏览器中可用,但在较早的版本中不可用。 也许Chrome或Firefox可以实现它,但Safari iOS和Edge却不能。
For example, ES6 introduced thearrow function:
例如,ES6引入了箭头功能:
[1, 2, 3].map((n) => n + 1)
Which is now supported by all modern browsers. IE11 does not support it, nor Opera Mini (How do I know? By checking the ES6 Compatibility Table).
现在所有现代浏览器都支持该功能。 IE11不支持它,也不支持Opera Mini(我怎么知道?通过检查ES6兼容性表 )。
So how should you deal with this problem? Should you move on and leave those customers with older/incompatible browsers behind, or should you write older JavaScript code to make all your users happy?
那么您应该如何处理这个问题呢? 您应该继续前进,让那些使用较旧/不兼容浏览器的客户留下来,还是应该编写较旧JavaScript代码使所有用户满意?
Enter Babel. Babel is acompiler: it takes code written in one standard, and it transpiles it to code written into another standard.
输入Babel。 Babel是一个编译器:它采用一种标准编写的代码,然后将其转换为另一种标准编写的代码。
You can configure Babel to transpile modern ES JavaScript into JavaScript ES5 syntax:
您可以配置Babel将现代ES JavaScript转换为JavaScript ES5语法:
[1, 2, 3].map(function(n) {return n + 1})
This must happen at build time, so you must setup a workflow that handles this for you. Webpack is a common solution.
这必须在构建时发生,因此您必须设置一个可以为您处理的工作流。 Webpack是常见的解决方案。
(P.S. if all thisESthing sounds confusing to you, see more about ES versions in the ECMAScript guide)
(PS,如果所有这些ES事情听起来令人困惑,请参阅ECMAScript指南中有关ES版本的更多信息)
安装Babel (Installing Babel)
Babel is easily installed using npm, locally in a project:
使用npm可以轻松地在项目中本地安装Babel:
npm install --save-dev @babel/core @babel/cli
In the past I recommended installing
babel-cli
globally, but this is now discouraged by the Babel maintainers, because by using it locally you can have different versions of Babel in each project, and also checking in babel in your repository is better for team work过去,我建议在全球范围内安装
babel-cli
,但是现在Babel维护人员不建议这样做,因为通过在本地使用它,您可以在每个项目中使用不同版本的Babel,并且在存储库中检入babel更适合团队工作
Since npm now comes withnpx
, locally installed CLI packages can run by typing the command in the project folder:
由于npm现在随附npx
,因此可以通过在项目文件夹中键入命令来运行本地安装的CLI软件包:
So we can run Babel by just running
这样我们就可以通过运行Babel
npx babel script.js
Babel配置示例 (An example Babel configuration)
Babel out of the box does not do anything useful, you need to configure it and add plugins.
Babel开箱即用并没有做任何有用的事情,您需要对其进行配置并添加插件。
Here is a list of Babel plugins
这是Babel插件的列表
To solve the problem we talked about in the introduction (using arrow functions in every browser), we can run
为了解决我们在简介中讨论的问题(在每个浏览器中使用箭头功能),我们可以运行
npm install --save-dev \@babel/plugin-transform-arrow-functions
to download the package in thenode_modules
folder of our app, then we need to add
将该包下载到我们应用程序的node_modules
文件夹中,那么我们需要添加
{"plugins": ["@babel/plugin-transform-arrow-functions"]}
to the.babelrc
file present in the application root folder. If you don’t have that file already, you just create a blank file, and put that content into it.
到应用程序根文件夹中存在的.babelrc
文件。 如果还没有该文件,则只需创建一个空白文件,然后将其内容放入其中。
TIP: If you have never seen a dot file (a file starting with a dot) it might be odd at first because that file might not appear in your file manager, as it’s a hidden file.
提示:如果您从未见过点文件(以点开头的文件),乍一看可能很奇怪,因为该文件可能不会出现在文件管理器中,因为它是隐藏文件。
Now if we have ascript.js
file with this content:
现在,如果我们有一个包含以下内容的script.js
文件:
var a = () => {};var a = (b) => b;const double = [1,2,3].map((num) => num * 2);console.log(double); // [2,4,6]var bob = {_name: "Bob",_friends: ["Sally", "Tom"],printFriends() {this._friends.forEach(f =>console.log(this._name + " knows " + f));}};console.log(bob.printFriends());
runningbabel script.js
will output the following code:
运行babel script.js
将输出以下代码:
var a = function () {};var a = function (b) {return b;};const double = [1, 2, 3].map(function (num) {return num * 2;});console.log(double); // [2,4,6]var bob = {_name: "Bob",_friends: ["Sally", "Tom"],printFriends() {var _this = this;this._friends.forEach(function (f) {return console.log(_this._name + " knows " + f);});}};console.log(bob.printFriends());
As you can see arrow functions have all been converted to JavaScript ES5 functions.
如您所见,箭头函数已全部转换为JavaScript ES5函数。
Babel预设 (Babel presets)
We just saw in the previous article how Babel can be configured to transpile specific JavaScript features.
我们刚刚在上一篇文章中看到了如何配置Babel来转换特定JavaScript功能。
You can add much more plugins, but you can’t add to the configuration features one by one, it’s not practical.
您可以添加更多的插件,但是不能一一添加到配置功能中,这是不实际的。
This is why Babel offerspresets.
这就是Babel提供预设的原因。
The most popular presets areenv
andreact
.
最受欢迎的预设是env
和react
。
Tip: Babel 7 deprecated (and removed) yearly presets like
preset-es
, and stage presets. Use@babel/preset-env
instead.提示:Babel 7已弃用(并删除了)每年的预设,例如
preset-es
和舞台预设。 请改用@babel/preset-env
。
env
预设 (env
preset)
Theenv
preset is very nice: you tell it which environments you want to support, and it does everything for you,supporting all modern JavaScript features.
env
预设非常好:您告诉它要支持的环境,它可以为您完成所有工作,并支持所有现代JavaScript功能。
E.g. “support the last 2 versions of every browser, but for Safari let’s support all versions since Safari 7`
例如,“支持每个浏览器的最后2个版本,但对于Safari,我们支持Safari 7之后的所有版本。
{"presets": [["env", {"targets": {"browsers": ["last 2 versions", "safari >= 7"]}}]]}
or “I don’t need browser support, just let me work with Node.js 6.10”
或“我不需要浏览器支持,只需让我使用Node.js 6.10”
{"presets": [["env", {"targets": {"node": "6.10"}}]]}
react
预设 (react
preset)
Thereact
preset is very convenient when writing React apps: addingpreset-flow
,syntax-jsx
,transform-react-jsx
,transform-react-display-name
.
在编写React应用程序时,react
预置非常方便:添加preset-flow
,syntax-jsx
,transform-react-jsx
,transform-react-display-name
。
By including it, you are all ready to go developing React apps, with JSX transforms and Flow support.
通过包含它,您已经准备好使用JSX转换和Flow支持来开发React应用程序。
有关预设的更多信息 (More info on presets)
https://babeljs.io/docs/plugins/
https://babeljs.io/docs/plugins/
将Babel与Webpack一起使用 (Using Babel with webpack)
If you want to run modern JavaScript in the browser, Babel on its own is not enough, you also need to bundle the code. Webpack is the perfect tool for this.
如果您想在浏览器中运行现代JavaScript,单凭Babel是不够的,您还需要捆绑代码。 Webpack是实现此目的的完美工具。
TIP: read the webpack guide if you’re not familiar with webpack
提示:如果您不熟悉Webpack,请阅读Webpack指南
Modern JS needs two different stages: a compile stage, and a runtime stage. This is because some ES6+ features need a polyfill or a runtime helper.
现代JS需要两个不同的阶段:编译阶段和运行时阶段。 这是因为某些ES6 +功能需要polyfill或运行时帮助程序。
To install the Babel polyfill runtime functionality, run
要安装Babel polyfill运行时功能,请运行
npm install @babel/polyfill \@babel/runtime \@babel/plugin-transform-runtime
Now in yourwebpack.config.js
file add:
现在在您的webpack.config.js
文件中添加:
entry: ['babel-polyfill',// your app scripts should be here],module: {loaders: [// Babel loader compiles ES into ES5 for// complete cross-browser support{loader: 'babel-loader',test: /\.js$/,// only include files present in the `src` subdirectoryinclude: [path.resolve(__dirname, "src")],// exclude node_modules, equivalent to the above lineexclude: /node_modules/,query: {// Use the default ES preset// to include all ES featurespresets: ['es'],plugins: ['transform-runtime']}}]}
By keeping the presets and plugins information inside thewebpack.config.js
file, we can avoid having a.babelrc
file.
通过将预设和插件信息保留在webpack.config.js
文件中,我们可以避免使用.babelrc
文件。
翻译自: /babel/
巴别塔圣经