使用 Encore 配置 Babel
Babel 通过 babel-loader
为所有 .js
和 .jsx
文件自动配置,并带有合理的默认值 (例如,如果需要,带有 @babel/preset-env
和 @babel/preset-react
)。
需要进一步扩展 Babel 配置?最简单的方法是通过 configureBabel()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// webpack.config.js
// ...
Encore
// ...
.configureBabel(function(babelConfig) {
// add additional presets
babelConfig.presets.push('@babel/preset-flow');
// no plugins are added by default, but you can add some
babelConfig.plugins.push('styled-jsx/babel');
}, {
// node_modules is not processed through Babel by default
// but you can allow some specific modules to be processed
includeNodeModules: ['foundation-sites'],
// or completely control the exclude rule (note that you
// can't use both "includeNodeModules" and "exclude" at
// the same time)
exclude: /bower_components/
})
;
配置浏览器目标
@babel/preset-env
预设会重写你的 JavaScript,以便最终的语法可以在你想要的任何浏览器中工作。要配置你需要支持的浏览器,请参阅 带有 Webpack Encore 的 PostCSS 和自动添加前缀 (postcss-loader)。
更改 "browserslist" 配置后,你需要手动删除 babel 缓存目录
1 2
# On Unix run this command. On Windows, clear this directory manually
$ rm -rf node_modules/.cache/babel-loader/
如果你想自定义 preset-env
配置,请使用 configureBabelPresetEnv()
方法来添加任何 @babel/preset-env 配置选项
1 2 3 4 5 6 7 8 9 10 11
// webpack.config.js
// ...
Encore
// ...
.configureBabelPresetEnv((config) => {
config.useBuiltIns = 'usage';
config.corejs = 3;
})
;
创建 .babelrc
文件
你可以创建项目根目录下的 .babelrc
文件,而不是调用 configureBabel()
。这是一种更“标准”的配置 Babel 的方式,但它有一个缺点:一旦存在 .babelrc
文件,Encore 将无法再为你添加任何 Babel 配置。例如,如果你调用 Encore.enableReactPreset()
,react
预设将不会自动添加到 Babel:你必须自己在 .babelrc
中添加它。
一旦存在 .babelrc
文件,它将优先于 Encore 添加的 Babel 配置。
这项工作,包括代码示例,根据 Creative Commons BY-SA 3.0 许可协议获得许可。