使用babel转换js为_如何仅使用babel即可快速转换javascript babel js简介

使用babel转换js为

JavaScript:工具 (JavaScript: Tooling)

You might have heard of Webpack, Rollup, or perhaps Parcel. These are some of the widely popular (web) bundling tools. What is bundling you ask? I think you are a little late to the party. Bundling, in a nutshell, is merging on two or more .js files together to form a single bundle file such as main.js. But this would be a far simplified definition. You could have used Gulp or Grunt for that.

您可能听说过WebpackRollupParcel 。 这些是一些非常流行的( web )捆绑工具。 您问的捆绑商品是什么? 我想你参加聚会有点晚了。 简而言之,捆绑是将两个或多个.js文件合并在一起以形成单个捆绑文件,例如main.js 但这将是一个大大简化的定义。 您可能为此使用了GulpGrunt

Bundling tools such as Webpack webpack can do much more than that. It can transpile your code from ES6 (or higher) to ES5 (or lower). It can also transpile programs written TypeScript or React to vanilla JavaScript as well as SASS/LESS to CSS. It can also automate a lot of things such as creating asynchronous bundles (chunks), compressing images, relocating builds, etc.

诸如Webpack webpack之类的捆绑工具可以做的还不止这些。 它可以将您的代码从ES6( 或更高版本 )转换为ES5( 或更低版本 )。 它还可以将编写TypeScriptReact的程序转换为原始JavaScript以及将SASS / LESS转换为CSS。 它还可以使很多事情自动化,例如创建异步捆绑( ),压缩映像,重新定位构建等。

💡 The word transpile means to compile a program from a higher programming language such as TypeScript to another high programming language such as JavaScript. The output programming language could be the same as input such as ES6 to ES5 transpilation. I will be using this word interchangeably with “compile” in this article but it means the same thing.

trans单词Transpile意味着将程序从高级编程语言(例如TypeScript)编译为另一种高级编程语言(例如JavaScript)。 输出编程语言可以与输入相同,例如从ES6到ES5的转换。 在本文中,我将这个词与“ compile ”互换使用,但这是同一回事。

As you can see, Webpack takes away a lot of manual work from the web development process and all you are left away with is the actual coding which is what every organization thrives to achieve. Hence, you will see Webpack (or others) being used in almost every organization and most projects.

如您所见,Webpack从Web开发过程中省去了许多手工工作,而您所剩下的只是实际的编码,这是每个组织都渴望实现的目标。 因此,您将看到几乎每个组织和大多数项目都在使用Webpack( 或其他 )。

The famous Angular framework uses Webpack under the hood to compile the Angular project which is primarily written in TypeScript. Though React is not a framework, but the create-react-app CLI tool helps you initialize an empty React project with a boilerplate that contains Webpack configuration to transpile React (JSX) to JavaScript and bundle your code for deployment.

著名的Angular框架在后台使用Webpack来编译主要用TypeScript编写的Angular项目。 尽管React不是一个框架,但是create-react-app CLI工具可以帮助您使用包含Webpack配置的样板初始化一个空的React项目,以将React( JSX )转换为JavaScript并捆绑您的代码以进行部署。

Trust me, setting up Webpack is no joke. I have written an article on how to create JavaScript plugins using Webpack and you can follow this lesson to understand this setup process. But the effort you put in setting up a better Webpack configuration earlier will immensely pay off in the future.

相信我,设置Webpack并不是开玩笑。 我写了一篇有关如何使用Webpack创建JavaScript插件的文章,您可以按照本课程来理解此设置过程。 但是您尽早建立更好的Webpack配置所付出的努力将在将来获得巨大回报。

However, sometimes you do not want the full capability of the bundling process that Webpack provides. Most of the time, we just want to transpile ES6 code to ES5. For example, you may want to use ES6 Arrow Function expression and ES6 Class syntax in the program but since they are ES6 features and may not be supported in all browsers, you want to transpile them to normal function declarations and constructor function expression.

但是,有时您不想要Webpack提供的捆绑过程的全部功能。 大多数时候,我们只想将ES6代码转换为ES5。 例如,您可能要在程序中使用ES6箭头函数表达式和ES6类语法,但是由于它们是ES6功能,并且并非在所有浏览器中都受支持,因此您希望将它们转换为普通function声明和构造函数表达式。

For this purpose, setting up Webpack probably isn’t worth the effort. This is a very small task and there must be a tool that can do this easily, perhaps just by invoking a CLI command. Luckily, we have such a tool.

为此,设置Webpack可能不值得。 这是一项非常小的任务,并且必须有一个可以轻松实现此目的的工具,也许只需调用CLI命令即可。 幸运的是,我们有这样的工具。

Before we dive into this tool, let me clarify something. One misunderstanding people have about Webpack is that Webpack does everything on its own. In reality, Webpack is merely just a bundling tool and it can’t do transpilation of TypeScript to JavaScript or SASS to CSS. So who does that?

在我们深入研究此工具之前,让我先澄清一下。 人们对Webpack的一个误解是Webpack独自完成所有事情。 实际上,Webpack只是一个捆绑工具,它不能将TypeScript转换为JavaScript或将SASS转换为CSS。 那是谁呢?

Webpack provides APIs to hook into the compilation process and manipulate the source code and build artifacts (output files). Webpack depends on loaders and plugins for this.

Webpack提供了一些API,可以挂入编译过程并操纵源代码并构建工件( 输出文件 )。 Webpack为此依赖于加载程序插件

A loader is an external program that Webpack invokes with the source code of a input program file. The loader transforms this code and returns it back to Webpack. This the crux of the transpilation process that the loader is performing. So if Webpack imports .ts file, it may call ts-loader which transforms TypeScript code to JavaScript.

加载程序是Webpack用输入程序文件的源代码调用的外部程序。 加载程序将转换此代码,并将其返回给Webpack。 这是加载程序正在执行的转译过程的关键。 因此,如果Webpack导入.ts文件,它可能会调用ts-loader ,它将TypeScript代码转换为JavaScript。

A plugin is an external program that hooks into different lifecycle events of the Webpack and performs some operation. For example, the widely used HtmlWebpackPlugin plugin listens to Webpack’s emit event and injects path of the output JavaScript and CSS files inside a .html file. This way, you do not need to manually import compiled files inside the .html file.

插件是一个外部程序,可以挂接到Webpack的不同生命周期事件并执行某些操作。 例如,广泛使用的HtmlWebpackPlugin插件侦听Webpack的emit事件,并将输出JavaScript和CSS文件的路径插入.html文件中。 这样,您无需手动将.html文件中的已编译文件导入。

Now lets come to the topic of the article. Babel is a JavaScript compiler and not a webpack loader. It compiles (transpiles) higher JavaScript code (ES6+) to lower JavaScript code (such as ES5). However, Babel doesn’t come as a single package but rather as individual NPM modules.

现在让我们进入本文的主题。 BabelJavaScript编译器,而不是Webpack加载器。 它将较高JavaScript代码( ES6 + )编译( 转换 )为较低JavaScript代码( 例如ES5 )。 但是,Babel并不是作为一个单独的软件包出现,而是作为单独的NPM模块出现。

The @babel/core package is the brain of Babel that orchestrates the compilation process. It provides APIs to transpile a JavaScript program file from a higher JavaScript version to a lower JavaScript version. You can import this package inside your own JavaScript program and use the APIs make a custom JavaScript compiler out of it.

@babel/core软件包是Babel的大脑,负责协调编译过程。 它提供API以将JavaScript程序文件从较高JavaScript版本转换为较低JavaScript版本。 您可以将此包导入自己JavaScript程序中,并使用API​​从中生成自定义JavaScript编译器。

The @babel/cli package gives you the babel command to compile JavaScript files from the command-line interface. For example, $ babel main.js command would transpile the main.js file. This package uses the @babel/core package under the hood for the compilation.

@babel/cli包使您可以使用babel命令从命令行界面编译JavaScript文件。 例如, $ babel main.js命令将转换main.js文件。 该软件包在内部使用@babel/core软件包进行编译。

Another misunderstood bit is that “the @babel/core package does the compilation of JavaScript” which is not quite right. The @babel/core package is just an orchestrator. Consider it as a middle person between a program that imports it (or the babel command) and the program that actually does the transpilation.

另一个被误解的地方是“ @babel/core包执行JavaScript的编译”,这不太正确。 @babel/core包只是一个协调器。 将其视为导入它的程序( babel 命令 )与实际进行转译的程序之间的中间人。

In the Babel universe, we have two more pieces of the puzzle, viz. plugin and preset. The plugin is the program that does the actual transpilation of a JavaScript feature. For example, @babel/plugin-transform-arrow-functions plugin transpiles ES6 Arrow Functions to ES5 function expressions.

在Babel宇宙中,我们还有另外两个难题,也就是。 插件预设 。 该plugin是执行JavaScript功能实际转换的程序。 例如, @babel/plugin-transform-arrow-functions插件将ES6 Arrow Functions转换为ES5 function表达式。

// from (input)var a = () => {};// to (output)var a = function () {};

You will also find Babel plugins to transpile ES6 class declarations, let and const declarations, spread operator, and much more. You can find the full list of official plugins from this document. You can configure Babel to only support plugins of your choice and leave other JavaScript features intact.

您还将找到Babel插件来转换ES6 class声明, letconst声明, 传播运算符等。 您可以从文档中找到官方插件的完整列表。 您可以将Babel配置为仅支持您选择的插件,而其他JavaScript功能保持不变。

So when a program asks @babel/core package to transpile a JavaScript program, it uses these plugins to perform transpilation of the individual JavaScript features. After the input program is passed through all the provided plugins, Babel will output the compiled result.

因此,当程序要求@babel/core程序包转换JavaScript程序时,它将使用这些插件对各个JavaScript功能进行转换。 输入程序通过所有提供的插件传递后,Babel将输出编译后的结果。

However, as you can see from this document, the list of plugins is huge. If you want to transpile all the JavaScript features, then it would be a nightmare to install these plugins manually one at a time and configure Babel for them.

但是,从本文档可以看到,插件列表非常庞大。 如果您想转换所有JavaScript功能,那么一次手动安装这些插件并为其配置Babel将是一场噩梦。

This is where presets come into play. A preset in a nutshell is a collection of Babel plugins. For example, the @babel/preset-es2015 preset is a collection of Babel plugins that transpiles ES2015 (ES6) features. However, year-wise presets are deprecated and you should use @babel/preset-env instead.

这是预设起作用的地方。 简而言之, 预设是Babel插件的集合。 例如, @babel/preset-es2015预设是Babel插件的集合,这些插件可转换ES2015( ES6 )功能。 但是,不建议按年使用预置,而应该使用@babel/preset-env

The @babel/preset-env preset is a smart preset that takes a call on what Babel plugins to use for transpilation based on a configuration. For example, you can provide this plugin a configuration about the browsers and their minimal version you want to support and it will figure out what JavaScript features are supported by the browser and what needs to be transpiled

@babel/preset-env预设是一个智能预设,它根据配置调用要使用的Babel插件进行移植。 例如,您可以为该插件提供有关您要支持的浏览器及其最低版本的配置,它将确定浏览器支持哪些JavaScript功能以及需要翻译哪些功能

{
"targets": {
"chrome": "58",
"ie": "11"
}
}

💡 Babel officially provides the @babel/preset-typescript preset to transpile TypeScript code to JavaScript and the @babel/preset-react preset to transpile React (JSX) code to JavaScript.

bel Babel正式提供@babel/preset-typescript typescript预设,以将TypeScript代码转换为JavaScript,并提供@babel/preset-react预设,以将React( JSX )代码转换为JavaScript。

When Babel transpile a JavaScript feature, it may use helper functions. A helper function is just a normal Javascript function that contains the logic to support a new JavaScript feature in the old JavaScript version. For example, the @babel/plugin-transform-instanceof plugin transpiles instanceof operator for older browsers using the _instanceof helper function.

当Babel转换JavaScript功能时,它可能会使用辅助函数。 辅助函数只是一个普通的Javascript函数,其中包含支持旧JavaScript版本的新JavaScript功能的逻辑。 例如, @babel/plugin-transform-instanceof插件使用_instanceof helper函数为较旧的浏览器转换了instanceof运算符。

// from (input)foo instanceof Bar;// to (output)
function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return right[Symbol.hasInstance](left); } else { return left instanceof right; } }_instanceof(foo, Bar);

💡 Since instanceof operator is it is not a new JavaScript feature, you must be thinking why we need to transpile it in the first place. This is because its behavior is now changed, thanks to Symbol.hasInstance method. You can read more about it from my article on the Symbol object.

💡由于instanceof运算符不是JavaScript的新功能,因此您必须首先考虑为什么需要转换它。 这是因为Symbol.hasInstance方法,现在其行为已更改。 您可以从有关Symbol对象的文章中了解更多信息。

In the above example, as you can see, Babel has replaced instanceof operator to _instanceof helper function call. This helper functions will be added to every input program file in the compilation if needed. This will lead to code duplication when multiple program files are involved in the compilation.

如您所见,在上面的示例中,Babel已将instanceof运算符替换为_instanceof辅助函数调用。 如果需要,此辅助函数将添加到编译中的每个输入程序文件中。 当编译中涉及多个程序文件时,这将导致代码重复。

Therefore Babel recommends implementing the @babel/plugin-transform-runtime plugin that uses @babel/runtime library to import these helper function. When this plugin is used, we get the following output.

因此,Babel建议实现使用@babel/runtime库导入这些帮助器功能的@babel/plugin-transform-runtime插件。 使用此插件时,我们得到以下输出。

// from (input)foo instanceof Bar;// to (output)
import { _instanceof } from '@babel/runtime';_instanceof(foo, Bar);

Though transpilation is the process of converting a feature implementation from a higher version to a lower version while talking about JavaScript transpilation, it doesn’t necessarily apply for all the features. For example, Promise and Symbol APIs aren’t transpiled by Babel and they are left intact.

尽管转译是在谈论JavaScript转译时将功能实现从较高版本转换为较低版本的过程,但不一定适用于所有功能。 例如,Babel不会编译PromiseSymbol API,它们会保持不变。

Unlike let, const, class , arrow functions and JavaScript features for which you will find Babel plugins, Promise and Symbol aren’t syntactical sugar. These are new JavaScript APIs that do not exist in older versions.

letconstclass ,arrow函数和JavaScript功能不同,您会发现Babel 插件PromiseSymbol不是语法糖。 这些是旧版本中不存在的新JavaScript API。

In such cases, Babel won’t transpile these and leave their implementations to us. Well, how would you implement these if they do not exist in older versions of JavaScript? This is where polyfills come into the picture. A polyfill is a JavaScript program that provides a missing JavaScript feature at runtime.

在这种情况下,Babel不会移植这些内容,而将其实现留给我们。 好吧,如果它们在旧版本JavaScript中不存在,您将如何实现它们? 这是polyfill进入图片的地方。 polyfill是一种JavaScript程序,可在运行时提供缺少JavaScript功能。

The promise-polyfill JavaScript package when imported using the simple import "promise-polyfill" statement or using the <script> tag injects Promise object in the global scope. Therefore a program that uses Promise API wouldn’t even notice if it is a polyfilled feature or native feature.

使用简单import "promise-polyfill"语句或使用<script>标记import "promise-polyfill"promise-polyfill JavaScript程序包将在全局范围内注入Promise对象。 因此,使用Promise API的程序甚至不会注意到它是polyfilled功能还是本机功能。

Babel provides @babel/polyfill package which provides polyfills for the major JavaScript APIs. But since Babel v7.4.0, this package has been deprecated in favor of core-js. Read more about this from here.

Babel提供了@babel/polyfill软件包,该软件包为主要JavaScript API提供了polyfill。 但是从Babel v7.4.0 ,不推荐使用此软件包,而推荐使用core-js从这里阅读更多有关此的内容。

import "core-js/stable";
import "regenerator-runtime/runtime";

The core-js and regenerator-runtime packages provide a perfect polyfilled runtime environment for modern JavaScript to run consistently on almost all browsers and JavaScript platforms. The regenerator-runtime package provides helper functions for code transpiled using the @babel/plugin-transform-regenerator plugin.

core-jsregenerator-runtime程序包为现代JavaScript提供了一个完美的,多填充的运行时环境,以在几乎所有浏览器和JavaScript平台上一致地运行。 regenerator-runtime软件包为使用@babel/plugin-transform-regenerator插件转译的代码提供了辅助功能。

The last piece of the puzzle is babel-loader. The babel-loader packge is the actual Webpack loader that transpiles JavaScript. It uses @babel/core and other plugins/presets we talked about. Its job is to take commands from Webpack and translate them to @babel/core API calls.

难题的最后一部分是babel-loaderbabel-loader packge是转译JavaScript的实际Webpack loader。 它使用@babel/core和我们讨论过的其他插件/预设。 它的工作是从Webpack获取命令并将其转换为@babel/core API调用。

⇨本地Babel安装 (⇨ Local Babel Installation)

First of all, let’s set up a simple project with a minimal package.json. You can create it using npm init or npm init -y command. Then we need to install @babel/core, @babel/preset-env packages for the development (compilation) and some polyfills for the runtime.

首先,让我们用最小的package.json设置一个简单的项目。 您可以使用npm initnpm init -y命令创建它。 然后,我们需要为开发( 编译 )安装@babel/core@babel/preset-env软件包,并为运行时安装一些polyfills。

$ npm init -y
$ npm install --save-dev @babel/core @babel/preset-env
$ npm install --save core-js regenerator-runtime

Now we are just missing one more piece and that is @babel/cli. This package provides us the ability to invoke @babel/core from the command-line interface. We can install this package locally or globally. First, we will install it locally and for that, we just need to install it in the normal fashion.

现在,我们只剩下一件了,那就是@babel/cli 。 该软件包使我们能够从命令行界面调用@babel/core 。 我们可以在本地或全局安装此软件包。 首先,我们将在本地安装它,为此,我们只需要以常规方式安装它即可。

$ npm install --save-dev @babel/cli

When we install @babel/cli locally, NPM creates a babel file (symlink to @babel/cli) inside node_modules/.bin directory of the project. This file is executed when the babel command is invoked by the user. But we can’t invoke this command globally as this package is installed locally.

当我们在本地安装@babel/cli ,NPM在项目的node_modules/.bin目录中创建一个babel文件( 符号链接到 @babel/cli )。 当用户调用babel命令时,将执行此文件。 但是我们无法全局调用此命令,因为此软件包是本地安装的。

Image for post
./ ./ node_modules/.bin/babelnode_modules/.bin/babel

We need to use $ node_modules/.bin/babel command to make it work. We could also use the babel command inside scripts of the package.json and NPM would gladly execute node_modules/.bin/babel for us.

我们需要使用$ node_modules/.bin/babel命令使其工作。 我们还可以在package.json scripts中使用babel命令,NPM会很乐意为我们执行node_modules/.bin/babel

// package.json{
"name": "babel-starter",
"scripts": {
"compile": "babel -f program.js"
}
}

Another cool trick is to use npx command. You can read more about this command from here. When you invoke npx babel command with some command-line arguments, it invokes the babel file inside node_modules/.bin which is neater than invoking $ node_modules/.bin/babel. So let’s test local installation of Babel using the npx babel --version command.

另一个很酷的技巧是使用npx命令。 您可以从此处阅读有关此命令的更多信息。 当您通过一些命令行参数调用node_modules/.bin npx babel命令时,它将调用node_modules/.bin内部的babel文件,这比调用$ node_modules/.bin/babel更整洁。 因此,让我们使用npx babel --version命令测试Babel的本地安装。

Image for post

As you can see from the above results, I have installed v7.10.5 of @babel/cli and v7.11.4 of @babel/core package. It’s time to compile program.js JavaScript program file using npx babel program.js command.

正如你可以从上面的结果看,我已经安装了v7.10.5@babel/cliv7.11.4@babel/core包。 现在该使用npx babel program.js命令编译program.js JavaScript程序文件了。

Image for post
program.jsprogram.js

If we look at the result, Babel didn’t do much here. It removed some unnecessary spaces and characters from the program and outputted the compiled program to the console (STDOUT).

如果我们看一下结果,Babel在这里没有做太多事情。 它从程序中删除了一些不必要的空格和字符,并将已编译的程序输出到控制台( STDOUT )。

This is actually the default Babel behavior. Since we haven’t configured Babel to use presets or plugins, it won’t transpile arrow function and let used in the program.js. To instruct Babel to use plugins and/or presets we have installed, we need a babel.config.json file in the project.

这实际上是默认的Babel行为。 由于我们还没有配置通天使用预设或插件,也不会transpile箭头功能, let在使用program.js 。 要指示Babel使用已安装的插件和/或预设,我们在项目中需要babel.config.json文件。

This JSON file mentions the plugins and presets we want to use in the compilation process. When babel command is invoked, Babel looks for this file in the root of the project.

该JSON文件提到了我们要在编译过程中使用的插件预设 。 调用babel命令时,Babel会在项目的根目录中查找此文件。

Image for post
babel.config.jsonbabel.config.json

💡 There are multiple ways to provide Babel configuration apart from the babel.config.json file. Read this documentation to know more.

the除了babel.config.json文件之外,还有多种方法可提供Babel配置。 阅读本文档以了解更多信息。

Now that we have configured Babel to use @babel/preset-env preset to transpile JavaScript features suitable for the Chrome 58 and Internet Explorer 11, we should be able to see different compilation result.

现在,我们已经将Babel配置为使用@babel/preset-env预设来转换适用于Chrome 58和Internet Explorer 11JavaScript功能,我们应该能够看到不同的编译结果。

Image for post
program.jsprogram.js

As you can see from the above result, Babel now compiled the arrow function expression to function expression as well as let keyword to var. Since you might want to store this result to a file, you can either redirect (>) the STDOUT to a file in the command itself or use the --out-file or simply the -o flag with the output file name.

从以上结果可以看出,Babel现在将arrow函数表达式编译为function表达式,并将let关键字编译为var 。 由于您可能希望将此结果存储到文件中,因此可以在命令本身中将STDOUT 重定向 ( > )到文件,或者使用--out-file或仅使用-o标志和输出文件名。

Image for post
out.jsout.js

Since you would need to execute this command every time you make changes to the program.js file, Babel provides the --watch or simply -w flag to watch for the file changes (program.js here) and compile whenever it detects the change in the source code of the file.

由于您每次对program.js文件进行更改时都需要执行此命令,因此Babel提供--watch或简单地-w标志来监视文件更改( program.js 在此处 ),并在检测到更改时进行编译program.js在文件的源代码中。

You may want to generate a source map for the input file (program.js here) to aid the debugging process. Babel can generate a source map file for you if you invoke the above command with --source-maps or simply -s flag.

您可能需要为输入文件( 此处program.js )生成源映射 ,以帮助调试过程。 如果您使用--source-maps或简单地-s标志调用上述命令,Babel可以为您生成一个源映射文件。

Image for post
out.jsout.js

As you can see from the above results, Babel has generated the out.js.map file which is the source map file for the out.js and it also injected the source map comment at the bottom of out.js file.

正如你可以从上面的结果看,巴贝尔已经产生out.js.map文件,该文件是为源地图文件out.js ,它也注入源地图评论在底部out.js文件。

💡 If you want to keep the source maps inline in the source file itself, use the inline value for the --source-maps flag such as --source-maps inline.

💡如果要在源文件本身中保持源地图的 ,请对--source-maps标志使用内联值,例如--source-maps inline

⇨全球Babel安装 (⇨ Global Babel Installation)

So far we have installed @babel/cli package locally due to which we had to use npx babelcommand. Local installation of @babel/cli package is ideal when you have multiple projects that support different versions of the Babel and/or different versions of Babel CLI.

到目前为止,由于必须使用npx babel命令,因此我们已经在本地安装了@babel/cli软件包。 当您有多个项目支持不同版本的Babel和/或不同版本的Babel CLI时, @babel/cli软件包的本地安装是理想的。

If you want to invoke babel command from anywhere on your system, we need to install @babel/cli globally so that you always have the babel command in the terminal. Since @babel/cli needs @babel/core package, we need to globally install that too.

如果要从系统上的任何位置调用babel命令,我们需要全局安装@babel/cli ,以便您始终在终端中使用babel命令。 由于@babel/cli需要@babel/core软件包,因此我们也需要全局安装。

$ npm install --global @babel/core @babel/cli

Once these packages are installed, you can execute babel command from anywhere. This command would work exactly like the npx babel command as it would use the babel.config.json file in the project’s root directory.

一旦安装了这些软件包,就可以在任何地方执行babel命令。 该命令将与babel.config.json npx babel命令完全一样,因为它将使用项目根目录中的babel.config.json文件。

Image for post
program.jsprogram.js

Though the global installation might seem enticing, I would recommend the local installation when it comes to commercial development. Since the global installation is up to the user, keeping the version of the @babel/core and @babel/cli consistent across multiple development machines is not possible with this approach.

尽管全局安装似乎很诱人,但在进行商业开发时,我还是建议您在本地安装。 由于全局安装取决于用户,因此使用这种方法无法在多个开发机器上保持@babel/core@babel/cli一致。

Since the versions of @babel/core and @babel/cli is locked by package-loca.json when the local installation is implemented, you will get the 100% reproducible builds across all development machines (when npm install command is used to install the project dependencies).

由于实施本地安装时@babel/core@babel/cli的版本已由package-loca.json锁定,因此您将在所有开发机上获得100%可复制的内部版本( 使用 npm install 命令安装项目依赖项 )。

处理填充料 (Handling Polyfills)

If you are working with Promises, Symbols, Generators, or any other JavaScript APIs that need polyfills, make sure you import the polyfills for them in the source program as shown below.

如果您正在使用Promises,Symbols,Generators或任何其他需要polyfillJavaScript API,请确保如下所示在源程序中为其导入polyfill。

Image for post
polyfill.jspolyfill.js

In the above example, the polyfill.js program implements Generators and Promise API. Since Babel do not transpile promises, we need to provide a polyfill for it which was done using the core-js/stable import.

在上面的示例中, polyfill.js程序实现了GeneratorsPromise API。 由于Babel不会兑现承诺,因此我们需要为其提供一个polyfill,它是使用core-js/stable导入完成的。

Since Generators are not supported in IE11, Babel transpiled it using the @babel/plugin-transform-regenerator plugin which has the dependency on regenerator-runtime package. Hence we imported that too. The output of the above program (polytest.out.js) looks like below.

由于IE11不支持Generators,Babel使用@babel/plugin-transform-regenerator插件对其进行了转译,该插件依赖于regenerator-runtime程序包。 因此,我们也导入了该内容。 上面程序( polytest.out.js )的输出如下所示。

gist.github.comgist.github.com

You can spot the helper function emitted by Babel in the output such as _toConsumableArray, _nonIterableSpread etc. By default, Babel does not use @babel/plugin-transform-runtime plugin to import them from the @babel/runtime package. So let’s install this plugin first.

您可以在输出中发现Babel发出的辅助函数,例如_toConsumableArray_nonIterableSpread等。默认情况下,Babel不使用@babel/plugin-transform-runtime插件从@babel/runtime包中导入它们。 因此,让我们先安装此插件。

$ npm install --save-dev @babel/plugin-transform-runtime
$ npm install --save @babel/runtime

The @babel/runtime package also needs to be installed since Babel would import these helper functions from this package (at runtime). Let’s add this plugin inside babel.config.json so that Babel can start using it.

还需要安装@babel/runtime软件包,因为Babel将从该软件包中导入这些帮助程序功能( 在运行时 )。 让我们在babel.config.json添加此插件,以便Babel可以开始使用它。

Image for post
babel.config.jsonbabel.config.json

Now when we compile the polytest.js file using the same command, we get the following output.

现在,当我们使用相同的命令编译polytest.js文件时,将获得以下输出。

gist.github.comgist.github.com

From the above result, now you can clearly see that the output does not contain the implementation of any helper function, rather the helper functions are being imported from the @babel/runtime package.

从以上结果中,您现在可以清楚地看到输出中不包含任何辅助函数的实现,而是从@babel/runtime包中导入了辅助函数。

There is one issue, however in the above file. We have imported the regenrator-runtime package but after integrating the @babel/plugin-transform-runtime plugin, Babel uses _regenrator import from the @babel/runtime package to support generators.

但是,以上文件中存在一个问题。 我们已经导入了regenrator-runtime程序包,但是在集成@babel/plugin-transform-runtime插件后,Babel使用从@babel/runtime包中的_regenrator import来支持生成器

This happens because by default, the @babel/plugin-transform-runtime plugin implements Regenerator aliasing. If we look at the default settings of this plugin, this will more evident.

发生这种情况是因为默认情况下, @babel/plugin-transform-runtime插件实现了Regenerator别名 。 如果我们查看此插件的默认设置 ,这将更加明显。

{
"plugins": [
[
"@babel/plugin-transform-runtime",
{
"absoluteRuntime": false,
"corejs": false,
"helpers": true,
"regenerator": true,
"useESModules": false,
"version": "7.0.0-beta.0"
}
]
]
}

Since the regenrator is set to true by default, Babel replaces regeneratorRuntime with _regenerator.default where _regenerator is imported from the @babel/runtime package. This is an effort to stop pollution of the global scope. But you can avoid this by simply setting regenrator to false in the babel.config.json as shown above.

由于regenrator设置为true 默认情况下 ,巴贝尔替换regeneratorRuntime_regenerator.default其中_regenerator从进口@babel/runtime包。 这是为了防止全球范围的污染 。 但是你可以通过简单的设置避免这种regenratorfalsebabel.config.json如上图所示。

💡 By default, Babel converts the ECMAScript import statements to CommonJS require() statements (used in Node.js runtime). If you want to preserve the import statements or transform it to something else such as amd, systemjs etc., then use the module setting of the preset (documented here).

💡默认情况下,Babel将ECMAScript import语句转换为CommonJS require()语句( 在Node.js运行时中使用 )。 如果要保留import语句或将其转换为amdsystemjs等其他名称,请使用预设的module设置( 在此处记录 )。

与Babel合作 (Doing more with Babel)

  • You can provide multiple source files with the babel command such as $ babel a.js b.js -o out.js.

    您可以使用babel命令提供多个源文件,例如$ babel a.js b.js -o out.js

  • You can compile all .js files from a directory by providing directory path as an input file. For example, $ babel src will compile all the .js files from the src directory. You can use--out-dir or simply the -d flag to output all compiled files into a directory or use the -o flag to combine them into a single bundle file.

    您可以通过提供目录路径作为输入文件来编译目录中的所有.js文件。 例如, $ babel src将编译src目录中的所有.js文件。 您可以使用--out-dir或仅使用-d标志将所有已编译的文件输出到目录中,或使用-o标志将它们组合为一个捆绑文件。

  • If you want to use a different filename for the Babel configuration file, you are free to do so. You can provide this file path using the --config-file flag such as $ babel --config-file babel.prod.json.

    如果要为Babel配置文件使用其他文件名,则可以随意使用。 您可以使用--config-file标志提供该文件路径,例如$ babel --config-file babel.prod.json

  • Read more about babel command and the Babel CLI interface from this documentation.

    文档中了解有关babel命令和Babel CLI界面的更多信息。

You do not need to go through the above setup process if you just need the boilerplate. Clone the following repository and get going.

如果只需要样板,则无需执行上述设置过程。 克隆以下存储库并继续。

Image for post
thatisuday.comthatisuday.com GitHubGitHub TwitterTwitter StackOverflowStackOverflow / / InstagramInstagram
Image for post

翻译自: https://medium.com/jspoint/how-to-quickly-transpile-javascript-using-babel-alone-a-brief-introduction-to-babel-js-40e74e43fe32

使用babel转换js为

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值