Babel 中文文档
  • 印记中文
  • 文档
  • 配置
  • 试用
  • 视频
  • 博客
  • 赞助
  • 团队
  • GitHub

使用 Babel

教你如何在使用 Babel 时选择工具

1选择你的工具 (尝试 CLI)

原型
在浏览器中
Babel 内置插件
CLIRequire hook
构建系统
BroccoliBrowserifyBrunchDuoGruntGulpjspmMakeMSBuildRequireJSRollupSprocketsWebpackStart
框架
EmberMeteorRailsSails
测试框架
AVAJasmineJestKarmaLabMocha
公用
ConnectNodemon
编程语言 APIs
C# / .NETNodeRuby
模板引擎
Pug
编辑器和 IDEs
WebStorm
调试工具
Node Inspector

2安装

npm install --save-dev @ava/babel

虽然你 可以 在你的机器上全局安装 Babel CLI, 但根据单个项目进行本地安装会更好一些。

这样做有两个主要的原因:

  1. 同一机器上的不同的项目可以依赖不同版本的 Babel, 这允许你一次更新一个项目。
  2. 这意味着在你的工作环境中没有隐含的依赖项。它将使你的项目更方便移植、更易于安装。

我们可以通过以下命令本地安装 Babel CLI:

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

注意: 如果你没有一个 package.json, 在安装之前请新建一个。这可以保证 npx 命令产生合适的交互。

在完成安装之后,你的 package.json 文件应该包括:

{
  "devDependencies": {
+   "@babel/cli": "^7.0.0",
+   "@babel/core": "^7.0.0"
  }
}
npm install -g babel-node-debug
npm install @babel/register
npm install --save-dev broccoli-babel-transpiler

在浏览器中编译的用例非常有限, 因此如果你在生产环境下工作,你应该在服务端预编译脚本。 请查看 配置构建系统 了解更多信息。

你可以使用 @babel/babel-standalone 作为 Babel 的预编译版本,或者你自己在 Babel 基础之上运行一个 bundler。请查看下面的使用部分,了解如何将其用作脚本。

你还可以使用更多在线工具对脚本进行原型化:

  • Babel 官方提供的 REPL
  • CodeSandbox

运行 Babel 于在线编辑器上:

  • JSFiddle
  • JSBin
  • Codepen
  • JSitor
npm install --save-dev babelify @babel/core
npm install --save-dev babel-brunch
npm install babel-connect

.NET 对于 Babel 的支持由 ReactJS.NET 项目提供。核心库可以通过 NuGet 安装:

Install-Package React.Core
npm install --save-dev duo-babel
ember install ember-cli-babel
npm install --save-dev grunt-babel @babel/core
# Babel 7
npm install --save-dev gulp-babel @babel/core
npm install --save-dev @babel/register @babel/core

babel-jest is now automatically loaded by Jest and fully integrated. This step is only required if you are using babel-jest to transform TypeScript files.

npm install --save-dev babel-jest

运行 jspm init -p 时选择 babel 作为编译器,或者用以下命令将现有的工程切换到 Babel 中:

jspm dl-loader --babel

The jspm package management CLI has been deprecated as of June 2020. See jspm repo for more details.

npm install --save-dev karma-babel-preprocessor @babel/core
npm install --save-dev lab-babel

在多数 Unix 系统中已经预装过。 Windows 系统可以从 gow 获取。

npm install metalsmith-babel

As of Meteor 1.2, the ecmascript package is installed by default for all new apps.

meteor add ecmascript
npm install --save-dev @babel/register @babel/core

ReactJS.NET 项目提供 ASP.NET 4.x 以上 Babel 支持。通过 NuGet 安装 MSBuild 任务:

Install-Package React.MSBuild
npm install --save-dev @babel/core
npm install @babel/core @babel/node --save-dev

jstransformer-babel supports Babel 6 only.

npm install jstransformer-babel

webpacker is the new default javascript compiler for Rails 6. It comes with built-in support for transpiling with babel. To use it in earlier versions of Rails:

# Gemfile
gem 'webpacker'
bundle install
bundle exec rails webpacker:install
npm install --save-dev requirejs-babel @babel/standalone babel-plugin-module-resolver-standalone
npm install --save-dev rollup
npm install --save-dev @rollup/plugin-babel
gem install babel-transpiler
npm install --save-dev sails-hook-babel
# Gemfile
gem "sprockets"
gem "sprockets-bumble_d"
bundle install
npm install --save @babel/core @babel/plugin-external-helpers @babel/plugin-transform-modules-umd @babel/preset-env
npm install -D start-babel
npm install --save-dev babel-loader @babel/core
npm install --save-dev @babel/cli

3用法

Enable Babel support either in package.json or ava.config.*

{
  "ava": {
    "babel": true
  }
}

请注意,AVA 总是 在转译你的插件时会添加一些自定义的 Babel 插件,请看 标注。

想要了解更多信息,请参阅 @ava/babel 仓库。

我们将把我们的指令放在本地版本的 npm 脚本中,而不是直接通过命令行来运行 Babel.

简单的在你的 package.json 中添加一个 "scripts" 属性并将 babel 命令放在它的 build 属性中。

  {
    "name": "my-project",
    "version": "1.0.0",
+   "scripts": {
+     "build": "babel src -d lib"
+   },
    "devDependencies": {
      "@babel/cli": "^7.0.0"
    }
  }

现在从我们的终端可以运行以下命令:

npm run build

这会按照和之前一样的方式来运行 Babel 并将输出放在 lib 目录下,唯一不同在于我们现在使用了一个本地拷贝。

另外,你可以在 node_modules 中引用 babel 命令。

./node_modules/.bin/babel src -d lib

了解完整 Babel CLI 文档请看 使用文档。

babel-node-debug path/to/script.js

或者使用这个命令:

bode-debug path/to/script.js

欲了解更多信息,请参阅 crabdude/babel-node-debug 项目。

使用它你需要在应用程序的入口起点顶部引入 Babel 。

require("@babel/register");

如果你在应用程序中使用 ES6 的 import 语法, 你则需要在入口起点的顶部引入 Babel ,以确保它优先加载:

import "@babel/register";

所有以 .es6, .es, .jsx 和 .js 扩展名为后缀的文件都能被 Babel 转译。 特殊的 polyfill 自然也需要引入特殊的 polyfill 。

不适合在库中使用

Require hook 会自动钩住所有节点需要的钩子。这将污染全局作用域,引发未知冲突。正因如此,它不适合在库中使用,但你如果正在编写一个应用程序,那么使用它就完全没问题。

不适合用于生产环境下

Require hook 主要推荐用于简单的情况下。

关于 Babel Require hook 的完整文档,请查看usage docs.

var babelTranspiler = require("broccoli-babel-transpiler");
var scriptTree = babelTranspiler(inputTree, options);

欲了解更多信息,请参阅 babel/broccoli-babel-transpiler 项目.

使用 @babel/standalone

<div id="output"></div>
<!-- 加载 Babel -->
<!-- <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> -->
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<!-- 你的脚本代码 -->
<script type="text/babel">
const getMessage = () => "Hello World";
document.getElementById('output').innerHTML = getMessage();
</script>

See docs for full documentation on @babel/standalone.

通过 CLI 使用

browserify script.js -t babelify --outfile bundle.js

通过 Node API 使用

browserify({ debug: true })
  .transform(babelify);

或者一个更完整的例子:

var fs = require("fs");
var browserify = require("browserify");
var babelify = require("babelify");

browserify({ debug: true })
  .transform(babelify)
  .require("./script.js", { entry: true })
  .bundle()
  .on("error", function (err) { console.log("Error: " + err.message); })
  .pipe(fs.createWriteStream("bundle.js"));

传递选项

CLI

browserify -d -e script.js -t [ babelify --comments false ]
Node API
browserify().transform(babelify.configure({
  comments: false
}))
package.json
{
  "transform": [["babelify", { "comments": false }]]
}

欲了解更多信息,请参阅 babel/babelify 项目。

就是这些!在你的 brunch 配置文件(例如: brunch-config.coffee)中设置 babel 选项,已经被内部处理的 filename 和 sourceMap 除外。

plugins:
  babel:
    whitelist: ["arrowFunctions"]
    format:
      semicolons: false

欲了解更多信息,请参阅 babel/babel-brunch 项目。

var babelMiddleware = require("babel-connect");

app.use(babelMiddleware({
  options: {
    // 转译文件使用到的选项
  },
  src: "assets",
  dest: "cache"
}));

app.use(connect.static("cache"));

欲了解更多信息,请参阅 babel/babel-connect 项目。

var babel = ReactEnvironment.Current.Babel;
// 转译一个文件
// 如果你也想要 source map, 那么可以使用 `TransformFileWithSourceMap`.
var result = babel.TransformFile("foo.js");
// 转译一段代码
var result = babel.Transform("class Foo { }");

通过 CLI

duo --use duo-babel

通过 Node API

Duo(root)
  .entry(entry)
  .use(babel)
  .run(fn);

欲了解更多信息,请参阅 babel/duo-babel 项目。

就是它了!

欲了解更多信息,请参阅 babel/ember-cli-babel 项目。

  export function* text () {
    yield this
      .source("src/**/*.js")
      .babel({ presets: ["env"] })
      .target("dist/")
  }

欲了解更多信息,请参阅 flyjs/fly-babel 项目。

var gobble = require("gobble");
module.exports = gobble("src").transform("babel", options);

欲了解更多信息,请参阅 babel/gobble-babel 项目。

grunt.initConfig({
  babel: {
    options: {
      sourceMap: true,
      presets: ["@babel/preset-env"],
    },
    dist: {
      files: {
        "dist/app.js": "src/app.js",
      },
    },
  },
});

grunt.loadNpmTasks('grunt-babel');

grunt.registerTask("default", ["babel"]);

欲了解更多信息,请参阅 babel/grunt-babel 项目。

var gulp = require("gulp");
var babel = require("gulp-babel");

gulp.task("default", function () {
  return gulp.src("src/app.js")
    .pipe(babel({
      presets: ["@babel/preset-env"]
    }))
    .pipe(gulp.dest("dist"));
});

和 source maps 一起使用

像这样使用 gulp-sourcemaps:

var gulp = require("gulp");
var sourcemaps = require("gulp-sourcemaps");
var babel = require("gulp-babel");
var concat = require("gulp-concat");

gulp.task("default", function () {
  return gulp.src("src/**/*.js")
    .pipe(sourcemaps.init())
    .pipe(babel())
    .pipe(concat("all.js"))
    .pipe(sourcemaps.write("."))
    .pipe(gulp.dest("dist"));
});

欲了解更多信息,请参阅 babel/gulp-babel 项目。

在你的 spec/support/jasmine.json 文件中作出如下变化:

{
  "helpers": [
    "../node_modules/@babel/register/lib/node.js"
  ]
}

这个文件在你通过 jasmine init 命令建立一个项目生成。Note that the file paths in helpers option are relative to spec_dir, not to project root path.

Create a babel.config.json in your project root:

{
  "presets": ["@babel/preset-env"]
}

欲了解更多信息,请参阅 piecioshka/test-jasmine-babel 项目。

在你的 package.json 文件中作出如下变化:

{
  "scripts": {
    "test": "jest"
  },
  "jest": {
    "transform": {
      "^.+\\.[t|j]sx?$": "babel-jest"
    }
  }
}

欲了解更多信息,请参阅 babel/babel-jest 项目。

当你在任何源代码中使用 import 或者 export 模块语法时 Babel 会自动启用。

对 JSX 的支持现在被 jspm 禁用。在 jspm 配置文件 `babelOptions` 中添加 `"blacklist": []` 可以重新启用它。

module.exports = function(config) {
  config.set({
    files: [
      "src/**/*.js",
      "test/**/*.js"
    ],
    preprocessors: {
      "src/**/*.js": ["babel"],
      "test/**/*.js": ["babel"]
    },
    "babelPreprocessor": {
      // options go here
      options: {
        presets: ["@babel/preset-env"],
        sourceMap: "inline"
      },
    }
  });
};

欲了解更多信息,请参阅 babel/karma-babel-preprocessor 项目。

当使用 lab 运行测试时,三个自古转译器为 lab-babel:

lab -T node_modules/lab-babel
SRC = $(wildcard src/*.js)
LIB = $(SRC:src/%.js=lib/%.js)

lib: $(LIB)
lib/%.js: src/%.js babel.config.json
  mkdir -p $(@D)
  babel $< -o $@
make

CLI

在你的 metalsmith.json 中添加 metalsmith-babel.

{
  "plugins": {
    "metalsmith-babel": {
      // babel 选项
      "presets": ["@babel/preset-env"]
    }
  }
}

API

var Metalsmith = require("metalsmith");
var babel = require("metalsmith-babel");

new Metalsmith("./source")
  .use(babel({
    /* babel 选项 */
    presets: ["@babel/preset-env"]
  }))
  .build(function(err, files) {
    if (err) {
      throw err;
    }

    console.log("Completed.");
  });

欲了解更多信息,请参阅 babel/metalsmith-babel 项目。

就是它了!任何以 .js 为扩展名的文件均会通过 Babel 被自动转译。

欲了解更多信息,请参阅 ecmascript README.md.

Mocha 8

在你的 package.json 文件中做如下变化:

Create .mocharc.yaml in your project root:

require:
  - '@babel/register'

有些特性需要一个 polyfill:

# Polyfills for builtin methods
npm install --save core-js

Add import polyfills before @babel/register.

require:
  - 'core-js'
  - '@babel/register'

Create babel.config.json in your project root:

{
  "presets": ["@babel/preset-env"]
}

For more information see the babel mocha-examples.

Mocha 3

--compilers is deprecated as of Mocha v4.0.0. See further explanation and workarounds.

{
  "scripts": {
    "test": "mocha --compilers js:@babel/register"
  }
}

通过 polyfill:

{
  "scripts": {
    "test": "mocha --require babel-polyfill --compilers js:@babel/register"
  }
}

在你的 MSBuild 脚本中都任务:

<UsingTask AssemblyFile="packages\React.MSBuild.2.1.0\React.MSBuild.dll" TaskName="TransformBabel" />

使用如下代码:

<TransformBabel SourceDir="$(MSBuildProjectDirectory)" TargetDir="" />

这样操作将会改变文件夹中每一个 .js 和 .jsx 文件,并同时对应生成一个 .generated.js 文件。

查看 guide 获取更多信息。

require("@babel/core").transform("code", {
  presets: ["@babel/preset-env"],
});

关于 Babel 的完整 API 文档请查阅使用文档。

在你的 package.json 文件做出如下改动:

{
  "scripts": {
    "babel-node": "babel-node --presets='@babel/preset-env' --ignore='foo|bar|baz'"
  }
}

然后通过以下命令调用你的脚本:

nodemon --exec npm run babel-node -- path/to/script.js

参数警告

使用 babel-node 调用 nodemon 时如果忘记使用双短划线,可能会导致错误地分析参数。 使用npm-scripts 来防止这一点。 如果您选择跳过使用 npm-scripts 脚本,它可以表示为:

nodemon --exec babel-node --presets=@babel/preset-env --ignore='foo\|bar\|baz' -- path/to/script.js

现在你可以在你的 pug 模板中使用 ES6, 如下所示:

script
  :babel
    console.log("Hello World !!!");
    class Person {
      constructor(name) {
        this.name = name;
      }
      sayName(){
        console.log(`Hello, my name is ${this.name}`);
      }
    }
    var person = new Person("Apoxx");
    person.sayName();

欲了解更多信息,请参阅 jstransformers/jstransformer-babel 项目。

That's it!

For more information see the rails/webpacker repo.

Alternatively, if you need babel to transpile javascript that's processed through sprockets, refer to the setup instructions for integrating babel with sprockets.

在配置中添加以下路径:

paths: {
    es6: '...node_modules/requirejs-babel/es6',
    babel: '...node_modules/@babel/standalone/babel.min',
    'babel-plugin-module-resolver': '...node_modules/babel-plugin-module-resolver-standalone/index'
  }

接下来,通过 es6! 加插件名引用文件:

define(["es6!your-es6-module"], function (module) {
  // ...
});

欲了解更多信息,请参阅 mikach/requirejs-babel 项目.

import babel from '@rollup/plugin-babel';

const config = {
  input: 'src/index.js',
  output: {
    dir: 'output',
    format: 'esm'
  },
  plugins: [babel({ babelHelpers: 'bundled' })]
};

export default config;

欲了解更多信息,请参阅 rollup 和 @rollup/plugin-babel 项目.

require 'babel/transpiler'
Babel::Transpiler.transform File.read("foo.es6")

欲了解更多信息,请参阅 babel/ruby-babel-transpiler 项目。

就是它了!

欲了解更多信息,请参阅 artificialio/sails-hook-babel 仓库。

# config/application.rb
extend Sprockets::BumbleD::DSL

configure_sprockets_bumble_d do |config|
  config.babel_config_version = 1
end

For more information see the rmacklin/sprockets-bumble_d repo.

import Start from 'start';
import reporter from 'start-pretty-reporter';
import files from 'start-files';
import read from 'start-read';
import babel from 'start-babel';
import write from 'start-write';

const start = Start(reporter());

export function build() {
  return start(
    files('lib/**/*.js'),
    read(),
    babel({ sourceMaps: true }),
    write('build/')
  );
}

欲了解更多信息,请参阅 start-runner/babel 项目。

通过 config 方式

{
  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ]
  }
}

欲了解更多信息,请参阅 babel/babel-loader 项目。

在 首选项 - 工具 - 文件观察 中,单击 + 按钮并从列表中选择 Babel 文件观察。

指定 Babel 可执行的文件路径,然后单击确定。

默认情况下,所有带有 .js 扩展名的文件都会在更改后自动与 Babel 一起编译。 生成的 ES5 文件和 source maps 将保存在原始文件旁。

最后,在 语言和框架 - JavaScript - JavaScript 语言版本中,选择 ECMAScript 6.

欲了解更多信息,请参阅 WebStorm 博客中的博文。

4创建 babel.config.json 配置文件

非常棒!虽然已经配置好了 Babel ,但并没有让它真正生效。在项目的根目录中创建一个 babel.config.json 文件并启用一些 presets。

首先,你可以使用转换 ES2015+ 的 env preset。

npm install @babel/preset-env --save-dev

为了让 preset 生效,你需要像下面这样定义你的 babel.config.json 文件:

{
  "presets": ["@babel/preset-env"]
}
Babel 中文文档
文档
学习 ES2015
社区
视频用户Stack OverflowSlack 频道Twitter
更多
博客GitHub 组织GitHub 仓库Website 仓库旧版网址 6.x旧版网址 5.x