巴别塔圣经

  • 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 the arrow 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 a compiler: 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 ES2017 JavaScript into JavaScript ES5 syntax:

您可以配置Babel将现代ES2017 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 this ES thing 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 with npx, 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 the node_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 a script.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());

running babel 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 offers presets.

这就是Babel提供预设的原因

The most popular presets are env and react.

最受欢迎的预设是envreact

Tip: Babel 7 deprecated (and removed) yearly presets like preset-es2017, and stage presets. Use @babel/preset-env instead.

提示:Babel 7已弃用(并删除了)每年的预设,例如preset-es2017和舞台预设。 请改用@babel/preset-env

env预设 (env preset)

The env 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)

The react preset is very convenient when writing React apps: adding preset-flow, syntax-jsx, transform-react-jsx, transform-react-display-name.

在编写React应用程序时, react预置非常方便:添加preset-flowsyntax-jsxtransform-react-jsxtransform-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 your webpack.config.js file add:

现在在您的webpack.config.js文件中添加:

entry: ['babel-polyfill',// your app scripts should be here
],module: {loaders: [// Babel loader compiles ES2015 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 ES2015 preset// to include all ES2015 featurespresets: ['es2015'],plugins: ['transform-runtime']}}]
}

By keeping the presets and plugins information inside the webpack.config.js file, we can avoid having a .babelrc file.

通过将预设和插件信息保留在webpack.config.js文件中,我们可以避免使用.babelrc文件。

翻译自: https://flaviocopes.com/babel/

巴别塔圣经

巴别塔圣经_巴别塔简短简要指南相关推荐

  1. 巴别塔圣经_承认巴别塔

    巴别塔圣经 by freeCodeCamp 通过freeCodeCamp 承认巴别塔 (Acknowledging the Tower of Babel) Note: this was origina ...

  2. c#简要程序设计_色彩在品牌设计方面的简要指南

    c#简要程序设计 Colors are the one of the most influential aspects of a given design, logo, or brand. When ...

  3. CGI简介用C来写CGI程序简要指南

    1. 什么是CGI? CGI 是通用网关接口(Common Gateway Interface)的缩写. 它主要用于服务器端动态输出客户端的请求(如,HTML页面/二进制文件). 也就是说客户端请求参 ...

  4. Chocolatey:Windows软件包管理系统_安装及使用指南

    Chocolatey: Windows软件包管理系统_安装及使用指南 Why chocolatey? Chocolatry是Windows下的软件包管理工具,可快速安装软件.Linux下通常使用apt ...

  5. java版农业银行_农行网上支付平台_商户接口编程指南-java_edition-v103.pdf

    农行网上支付平台_商户接口编程指南-java_edition-v103 Java Edition V1.0.3 –– 2003/ 11/26 V0.1 2003/ 12/ 10 V0.2 2003-1 ...

  6. CGI简介——用C来写CGI程序简要指南

    http://www.cnblogs.com/ribavnu/archive/2012/11/18/2775552.html 1. 什么是CGI ? CGI 是通用网关接口(Common Gatewa ...

  7. 如何使用vps 异地组网_异地组网简要配置指南

    Tag : 异地组网 异地组网简要配置指南 多台网关设备没有公网地址的情况下,需要能够互相访问各网关设备之间的局域网. 目前异地组网只支持星型网络,成功建立组网后,只允许从分支节点局域网访问中心节点的 ...

  8. 简短加密_神经网络训练中回调的简短实用指南

    简短加密 Callbacks are an important part of neural network training. These are actions that can be perfo ...

  9. python初学者编程指南_动态编程初学者指南

    python初学者编程指南 编程辅导 (PROGRAMMING TUTORIAL) Dynamic programming is an art, the more problems you solve ...

  10. 高斯金字塔 拉普拉斯金字塔_金字塔学入门指南

    高斯金字塔 拉普拉斯金字塔 The topic for today is on data validation and settings management using Python type hi ...

最新文章

  1. Spark源码分析 – SparkEnv
  2. 企业品牌网站建设都涉及收取哪些方面的费用?
  3. http://www.jianshu.com/p/42e11515c10f#
  4. 人工智能趋势:语音识别发展前景广阔
  5. 2018年11月26日 练习3
  6. 台式计算机电源机箱维修,台式电脑电源故障维修实例教程
  7. NSSM 制作 window 服务
  8. Qt: 解决Qt语言家 更新翻译(lupdate) 非常慢卡死没反应现象
  9. iphone5s已停用连接itunes怎么办?苹果5s已停用连接itunes解决方法
  10. Backdrop CMS介绍
  11. 双十一生活必买清单,经常失眠人士助眠好物推荐
  12. 连接问题:ORA-3136:inbound connection timed out
  13. mtk-lk display代码分析
  14. 一键调用API,聚合数据API服务助力企业应用创新
  15. 阿里巴巴九大美女高管个个身价上亿,你最佩服谁?
  16. 抛物线断面临界水深莫洛图
  17. NPM Error:gyp: No Xcode or CLT version detected!
  18. python控制台中怎么控制开始和结束_Python-基础篇之控制台编程 - 随笔分类 - 梦并不遥远 - 博客园...
  19. 区块链落地就看这一“会”了
  20. OC11_Block

热门文章

  1. 多元回归分析python实战-----对我国财政收入的多因素进行分析
  2. ADAS/AD控制器模块开发03 - 系统架构设计及通用需求定义
  3. java 算法之斐波那契数列
  4. ADB常用命令及详解
  5. orcad元件封装制作
  6. 如何使用Origin轻松绘制三点线段图
  7. 北大中文核心期刊目录2021年 电工技术
  8. 应用密码学第6章——第七章
  9. 数学建模论文写作要求
  10. 几款脑力训练软件分析与推荐