# Babel 插件

`@kokojs/plugin-babel` 基于 `babel` 提供 js 和 ts 的编译能力。

## 安装

```bash
yarn add @kokojs/plugin-babel --dev
```

安装完成后，在 `koko.config.js` 中添加如下配置：

```js
module.exports = {
  plugins: {
    babel: {},
  },
};
```

## 配置 Babel

koko 中不包含 babel 配置文件，因此需要在项目里自行配置。

- C 端应用：使用 [babel-preset-h5](/packages/@kokojs/babel-preset-h5/)
- B 端应用：使用 [babel-preset-pc](/packages/@youzan/babel-preset-pc/)

## 配置项

### presets

- Type: `PluginItem[]`
- Default: `undefined`

自定义 Babel Presets，详见 [Presets](https://babeljs.io/docs/en/presets)。

```js
// koko.config.js
module.exports = {
  plugins: {
    babel: {
      presets: ['@babel/preset-react'],
    },
  },
};
```

### plugins

- Type: `PluginItem[]`
- Default: `undefined`

自定义 Babel Plugins，详见 [Plugins](https://babeljs.io/docs/en/plugins)。

```js
// koko.config.js
module.exports = {
  plugins: {
    babel: {
      plugins: ['@babel/plugin-proposal-class-properties'],
    },
  },
};
```

### checkType

- Type: `boolean`
- Default: `true`

是否开启 TypeScript 编译时类型检查，基于 [fork-ts-checker-webpack-plugin](https://github.com/TypeStrong/fork-ts-checker-webpack-plugin) 实现。

项目中存在 `tsconfig.json` 文件时才会开启。

### scriptTranspile

- Type: `'dev' | 'build' | 'all' | 'none'`
- Default: `'all'`

是否开启 Babel 编译，默认开启。

- 值为 `dev` 时，表示仅在 dev 模式下开启
- 值为 `build` 时，表示仅在 build 模式下开启
- 值为 `all` 时，会在 dev & build 模式下开启
- 值为 `none` 时，表示不开启

### nodeModulesTransform

- Type: `'prod-only' | 'none'`
- Default: `'none'`

是否对 node_modules 中的代码进行编译，`prod-only` 表示只在生产环境构建时编译，`none` 表示不编译。

按照社区的约定，node_modules 中的前端库默认会提供 ES5 格式的代码，因此大部分工具不会对 node_modules 进行 babel 编译。

但是随着 ES6 语法的广泛运用，经常会出现未经编译的 ES6 代码被发布到 npm 的情况，并导致引入代码的项目出现线上兼容性问题。为了避免这样的问题，可以在以下两种方式中进行选择：

1. 使用 `compilePackages` 或 `nodeModulesTransform`，对 node_modules 中的代码采取基本的 babel 编译，这样做会对编译速度有一定影响。
2. 使用 `koko-plugin-es-guard`，检测 node_modules 中的 ES6 语法，并手动处理。

### compilePackages

- Type: `string[]`
- Default: `undefined`

需要编译的 npm 包列表，如果 node_modules 中存在使用 ESNext 语法的 npm 包，可以通过配置该选项进行编译。

```js
// koko.config.js
module.exports = {
  plugins: {
    babel: {
      compilePackages: ['query-string'],
    },
  },
};
```

## 维护者

陈嘉涵。
