Skip to content

docs(cn): translate src/content/loaders/babel-loaders.md #770

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 23, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 66 additions & 66 deletions src/content/loaders/babel-loader.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,23 @@ repo: https://github.com/babel/babel-loader



This package allows transpiling JavaScript files using [Babel](https://github.com/babel/babel) and [webpack](https://github.com/webpack/webpack).
package 允许你使用 [Babel](https://github.com/babel/babel) [webpack](https://github.com/webpack/webpack) 转译 `JavaScript` 文件。

**Note**: Issues with the output should be reported on the Babel [Issues](https://github.com/babel/babel/issues) tracker.
**注意**:请在 Babel [Issues](https://github.com/babel/babel/issues) tracker 上报告输出时遇到的问题。
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
**注意**:请在 Babel [Issues](https://github.com/babel/babel/issues) tracker 上报告输出时遇到的问题
**注意**:请在 Babel [Issues](https://github.com/babel/babel/issues) 追踪器上报告输出时遇到的问题

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tracker 不是专有门词,不需要翻译

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@QC-L 是翻译成追踪器吗?我看v4的中文文档里面tracker也是直接用的英文没翻译成追踪器

Copy link
Member

@QC-L QC-L Jun 23, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

从你的角度觉得 Issues tracker 好理解嘛?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tracker确实不好理解..但是感觉中文追踪器也不太好理解(从我的角度看)。如果没有合适的词那就追踪器吧

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

那就先追踪器吧


## Install
## 安装

> webpack 4.x | babel-loader 8.x | babel 7.x

```bash
npm install -D babel-loader @babel/core @babel/preset-env webpack
```

## Usage
## 用法

webpack documentation: [Loaders](/loaders/)
webpack 文档:[Loaders](/loaders/)

Within your webpack configuration object, you'll need to add the babel-loader to the list of modules, like so:
webpack 配置对象中,需要将 babel-loader 添加到 module 列表中,就像下面这样:

```javascript
module: {
Expand All @@ -43,11 +43,11 @@ module: {
}
```

### Options
### 选项

See the `babel` [options](https://babeljs.io/docs/en/options).
查看 babel [选项](https://babeljs.io/docs/en/options)

You can pass options to the loader by using the [`options`](/configuration/module/#ruleoptions--rulequery) property:
你可以使用 options 属性,来向 loader 传递 options [选项](/configuration/module/#ruleoptions--rulequery)

```javascript
module: {
Expand All @@ -67,42 +67,42 @@ module: {
}
```

This loader also supports the following loader-specific option:
loader 也支持下面这些 loader 特有的选项:

* `cacheDirectory`: Default `false`. When set, the given directory will be used to cache the results of the loader. Future webpack builds will attempt to read from the cache to avoid needing to run the potentially expensive Babel recompilation process on each run. If the value is set to `true` in options (`{cacheDirectory: true}`), the loader will use the default cache directory in `node_modules/.cache/babel-loader` or fallback to the default OS temporary file directory if no `node_modules` folder could be found in any root directory.
* `cacheDirectory`:默认值为 `false`。当有设置时,指定的目录将用来缓存 loader 的执行结果。之后的 webpack 构建,将会尝试读取缓存,来避免在每次执行时,可能产生的、高性能消耗的 Babel 重新编译过程(recompilation process)。如果设置了一个空值 (`loader: 'babel-loader?cacheDirectory'`) 或者 `true` (`loader: 'babel-loader?cacheDirectory=true'`),loader 将使用默认的缓存目录 `node_modules/.cache/babel-loader`,如果在任何根目录下都没有找到 `node_modules` 目录,将会降级回退到操作系统默认的临时文件目录。

* `cacheIdentifier`: Default is a string composed by the `@babel/core`'s version, the `babel-loader`'s version, the contents of `.babelrc` file if it exists, and the value of the environment variable `BABEL_ENV` with a fallback to the `NODE_ENV` environment variable. This can be set to a custom value to force cache busting if the identifier changes.
* `cacheIdentifier`:默认是由 `@babel/core` 版本号,`babel-loader` 版本号,`.babelrc` 文件内容(存在的情况下),环境变量 `BABEL_ENV` 的值(没有时降级到 `NODE_ENV`)组成的一个字符串。可以设置为一个自定义的值,在 identifier 改变后,来强制缓存失效。

* `cacheCompression`: Default `true`. When set, each Babel transform output will be compressed with Gzip. If you want to opt-out of cache compression, set it to `false` -- your project may benefit from this if it transpiles thousands of files.
* `cacheCompression`:默认值为 `true`。当设置此值时,会使用 Gzip 压缩每个 Babel transform 输出。如果你想要退出缓存压缩,将它设置为 `false` -- 如果你的项目中有数千个文件需要压缩转译,那么设置此选项可能会从中收益。

* `customize`: Default `null`. The path of a module that exports a `custom` callback [like the one that you'd pass to `.custom()`](#customized-loader). Since you already have to make a new file to use this, it is recommended that you instead use `.custom` to create a wrapper loader. Only use this if you _must_ continue using `babel-loader` directly, but still want to customize.
* `customize`: 默认值为 `null`。导出 `custom` 回调函数的模块路径,[例如传入 `.custom()` 的 callback 函数](#自定义-loader)。由于你必须创建一个新文件才能使用它,建议改为使用 `.custom` 来创建一个包装 loader。只有在你_必须_继续直接使用 `babel-loader` 但又想自定义的情况下,才使用这项配置。

## Troubleshooting
## 疑难解答

### babel-loader is slow!
### babel-loader 很慢!

Make sure you are transforming as few files as possible. Because you are probably matching `/\.m?js$/`, you might be transforming the `node_modules` folder or other unwanted source.
确保转译尽可能少的文件。你可能使用 `/\.m?js$/` 来匹配,这样也许会去转译 `node_modules` 目录或者其他不需要的源代码。

To exclude `node_modules`, see the `exclude` option in the `loaders` config as documented above.
要排除 `node_modules`,参考文档中的 `loaders` 配置的 `exclude` 选项。

You can also speed up babel-loader by as much as 2x by using the `cacheDirectory` option. This will cache transformations to the filesystem.
你也可以通过使用 `cacheDirectory` 选项,将 babel-loader 提速至少两倍。这会将转译的结果缓存到文件系统中。

### Babel is injecting helpers into each file and bloating my code!
### Babel 在每个文件都插入了辅助代码,使代码体积过大!

Babel uses very small helpers for common functions such as `_extend`. By default, this will be added to every file that requires it.
Babel 对一些公共方法使用了非常小的辅助代码,比如 `_extend`。默认情况下会被添加到每一个需要它的文件中。

You can instead require the Babel runtime as a separate module to avoid the duplication.
你可以引入 Babel runtime 作为一个独立模块,来避免重复引入。

The following configuration disables automatic per-file runtime injection in Babel, requiring `@babel/plugin-transform-runtime` instead and making all helper references use it.
下面的配置禁用了 Babel 自动对每个文件的 runtime 注入,而是引入 `@babel/plugin-transform-runtime` 并且使所有辅助代码从这里引用。

See the [docs](https://babeljs.io/docs/plugins/transform-runtime/) for more information.
更多信息请查看 [文档](https://babel.docschina.org/docs/en/babel-plugin-transform-runtime/)

**NOTE**: You must run `npm install -D @babel/plugin-transform-runtime` to include this in your project and `@babel/runtime` itself as a dependency with `npm install @babel/runtime`.
**注意**:你必须执行 `npm install -D @babel/plugin-transform-runtime` 来把它包含到你的项目中,然后使用 `npm install @babel/runtime` 把 `@babel/runtime` 安装为一个依赖。

```javascript
rules: [
// the 'transform-runtime' plugin tells Babel to
// require the runtime instead of inlining it.
// 'transform-runtime' 插件告诉 Babel
// 要引用 runtime 来代替注入。
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
Expand All @@ -117,9 +117,9 @@ rules: [
]
```

#### **NOTE**: transform-runtime & custom polyfills (e.g. Promise library)
#### **注意**:transform-runtime 和自定义 polyfills (例如 Promise library)

Since [@babel/plugin-transform-runtime](https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-runtime) includes a polyfill that includes a custom [regenerator-runtime](https://github.com/facebook/regenerator/blob/master/packages/regenerator-runtime/runtime.js) and [core-js](https://github.com/zloirock/core-js), the following usual shimming method using `webpack.ProvidePlugin` will not work:
由于 [@babel/plugin-transform-runtime](https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-runtime) 包含了一个 polyfill,含有自定义的 [regenerator-runtime](https://github.com/facebook/regenerator/blob/master/packages/regenerator-runtime/runtime.js) [core-js](https://github.com/zloirock/core-js), 下面使用 `webpack.ProvidePlugin` 来配置 shimming 的常用方法将没有作用:

```javascript
// ...
Expand All @@ -129,15 +129,15 @@ Since [@babel/plugin-transform-runtime](https://github.com/babel/babel/tree/mast
// ...
```

The following approach will not work either:
下面这样的写法也没有作用:

```javascript
require('@babel/runtime/core-js/promise').default = require('bluebird');

var promise = new Promise;
```

which outputs to (using `runtime`):
它其实会生成下面这样 (使用了 `runtime` 后):

```javascript
'use strict';
Expand All @@ -149,9 +149,9 @@ require('@babel/runtime/core-js/promise')['default'] = require('bluebird');
var promise = new _Promise();
```

The previous `Promise` library is referenced and used before it is overridden.
前面的 `Promise` library 在被覆盖前已经被引用和使用了。

One approach is to have a "bootstrap" step in your application that would first override the default globals before your application:
一种可行的办法是,在你的应用程序中加入一个“引导(bootstrap)”步骤,在应用程序开始前先覆盖默认的全局变量。

```javascript
// bootstrap.js
Expand All @@ -163,32 +163,32 @@ require('@babel/runtime/core-js/promise').default = require('bluebird');
require('./app');
```

### The Node.js API for `babel` has been moved to `babel-core`.
### `babel` 的 Node.js API 已经被移到 `babel-core` 中。

If you receive this message, it means that you have the npm package `babel` installed and are using the short notation of the loader in the webpack config (which is not valid anymore as of webpack 2.x):
如果你收到这个信息,这说明你有一个已经安装的 `babel` npm package,并且在 webpack 配置中使用 loader 简写方式(在 webpack 2.x 版本中将不再支持这种方式):
```javascript
{
test: /\.m?js$/,
loader: 'babel',
}
```

webpack then tries to load the `babel` package instead of the `babel-loader`.
webpack 将尝试读取 `babel` package 而不是 `babel-loader`

To fix this, you should uninstall the npm package `babel`, as it is deprecated in Babel v6. (Instead, install `@babel/cli` or `@babel/core`.)
In the case one of your dependencies is installing `babel` and you cannot uninstall it yourself, use the complete name of the loader in the webpack config:
想要修复这个问题,你需要卸载 `babel` npm package,因为它在 Babel v6 中已经被废除。(安装 `@babel/cli` 或者 `@babel/core` 来替代它)
在另一种场景中,如果你的依赖于 `babel` 而无法删除它,可以在 webpack 配置中使用完整的 loader 名称来解决:
```javascript
{
test: /\.m?js$/,
loader: 'babel-loader',
}
```

## Customize config based on webpack target
## 根据 webpack 部署目标(target)的自定义配置

Webpack supports bundling multiple [targets](/concepts/targets/). For cases where you may want different Babel configurations for each target (like `web` _and_ `node`), this loader provides a `target` property via Babel's [caller](https://babeljs.io/docs/en/config-files#apicallercb) API.
Webpack 支持打包成多种 [部署目标](/concepts/targets/) 。例如,当需要为不同的部署目标(例如 `web` _和_ `node`)指定不同的 Babel 配置时, babel-loader 通过 Babel[caller](https://babeljs.io/docs/en/config-files#apicallercb) API 提供了 `target`属性。

For example, to change the environment targets passed to `@babel/preset-env` based on the webpack target:
例如,根据 webpack 的部署目标改变传给`@babel/preset-env`的 targets选项

```javascript
// babel.config.js
Expand All @@ -204,7 +204,7 @@ module.exports = api => {
"@babel/preset-env",
{
useBuiltIns: "entry",
// caller.target will be the same as the target option from webpack
// caller.target 等于 webpack 配置的 target 选项
targets: api.caller(caller => caller && caller.target === "node")
? { node: "current" }
: { chrome: "58", ie: "11" }
Expand All @@ -215,23 +215,23 @@ module.exports = api => {
}
```

## Customized Loader
## 自定义 loader

`babel-loader` exposes a loader-builder utility that allows users to add custom handling
of Babel's configuration for each file that it processes.
`babel-loader` 提供了一个 loader-builder 工具函数,
允许用户为 Babel 处理过的每个文件添加自定义处理选项

`.custom` accepts a callback that will be called with the loader's instance of
`babel` so that tooling can ensure that it using exactly the same `@babel/core`
instance as the loader itself.
`.custom` 接收一个 callback 函数,
它将被调用,并传入 loader 中的 `babel` 实例,
因此,此工具函数才能够完全确保它使用与 loader 的 `@babel/core` 相同的实例。

In cases where you want to customize without actually having a file to call `.custom`, you
may also pass the `customize` option with a string pointing at a file that exports
your `custom` callback function.
如果你想自定义,但实际上某个文件又不想调用 `.custom`
可以向 `customize` 选项传入一个字符串,
此字符串指向一个导出 `custom` 回调函数的文件。

### Example
### 示例

```js
// Export from "./my-custom-loader.js" or whatever you want.
// "./my-custom-loader.js" 中导出,或者任何你想要的文件中导出。
module.exports = require("babel-loader").custom(babel => {
function myPlugin() {
return {
Expand All @@ -240,21 +240,21 @@ module.exports = require("babel-loader").custom(babel => {
}

return {
// Passed the loader options.
// 传给 loader 的选项。
customOptions({ opt1, opt2, ...loader }) {
return {
// Pull out any custom options that the loader might have.
// 获取 loader 可能会有的自定义选项
custom: { opt1, opt2 },

// Pass the options back with the two custom options removed.
// 传入"移除了两个自定义选项"后的选项
loader,
};
},

// Passed Babel's 'PartialConfig' object.
// 提供 Babel'PartialConfig' 对象
config(cfg) {
if (cfg.hasFilesystemConfig()) {
// Use the normal config
// 使用正常的配置
return cfg.options;
}

Expand All @@ -263,7 +263,7 @@ module.exports = require("babel-loader").custom(babel => {
plugins: [
...(cfg.options.plugins || []),

// Include a custom plugin in the options.
// 在选项中包含自定义 plugin
myPlugin,
],
};
Expand All @@ -272,15 +272,15 @@ module.exports = require("babel-loader").custom(babel => {
result(result) {
return {
...result,
code: result.code + "\n// Generated by some custom loader",
code: result.code + "\n// 自定义loader生成",
};
},
};
});
```

```js
// And in your Webpack config
// 然后,在你的 webpack config 文件中
module.exports = {
// ..
module: {
Expand All @@ -295,19 +295,19 @@ module.exports = {

### `customOptions(options: Object): { custom: Object, loader: Object }`

Given the loader's options, split custom options out of `babel-loader`'s
options.
指定的 loader 的选项,
从 `babel-loader` 选项中分离出自定义选项。


### `config(cfg: PartialConfig): Object`

Given Babel's `PartialConfig` object, return the `options` object that should
be passed to `babel.transform`.
指定的 Babel`PartialConfig` 对象,
返回应该被传递给 `babel.transform` 的 `option` 对象。


### `result(result: Result): Result`

Given Babel's result object, allow loaders to make additional tweaks to it.
指定的 Babel 结果对象,允许 loaders 对它进行额外的调整。


## License
Expand Down