在现代前端开发中,使用 webpack 构建工具来打包和优化代码已经成为了标配。而其中一个重要的工具就是 babel-loader,它可以将 ES6/ES7 甚至是未来版本的 JavaScript 语法转换为目前所有的浏览器都支持的 ES5 语法。在使用 babel-loader 的过程中,有一些高级配置可以让你更进一步提升构建的效率和性能。
为什么需要 babel-loader?
JavaScript 的语法在不断更新,但是不同的浏览器对于新旧语言特性的支持不同,而 babel-loader 可以帮助我们将最新的语法转换成所有浏览器都支持的 ES5 语法,以提高代码的兼容性。
babel-loader 的基础使用
babel-loader 的基础使用很简单,只需要在 webpack 配置文件中添加相应的 loader 即可。具体配置如下所示:
// www.javascriptcn.com code example
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
}
]
}其中,test 表示使用该 loader 处理的文件类型,exclude 表示该 loader 忽略的文件夹,而 presets 用于指定使用的转换规则,@babel/preset-env 表示使用最新的 ES6/ES7/ES8 的所有特性。
优化 babel-loader
虽然 babel-loader 的基本使用非常简单,但其实还有很多相关的高级配置可以优化代码的打包和转换效率。了解和配置这些选项可以更好的利用 babel-loader。
缓存 babel-loader 转换结果
由于 babel-loader 的转换规则非常复杂,甚至可能需要多个插件的联合,每次 webpack 构建时都重新转换会比较耗时。因此,可以使用 cacheDirectory 选项缓存转换的结果。这个选项可以将结果缓存至指定目录,webpack 构建时可以直接使用缓存结果,而不用重新转换,从而提高编译速度。
// www.javascriptcn.com code example
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets: ['@babel/preset-env']
}
}
}
]
}不将所有 babel-runtime 包打入代码包
使用 Babel 转换后,每个 JS 文件的顶部都需要引入 @babel/runtime/helpers 跟 @babel/runtime 必要的 polyfill 和 helpers,这样打包后的代码会变得臃肿不堪。因此,可以配置 @babel/plugin-transform-runtime + @babel/runtime-corejs2,避免重复打入,减小代码包大小。
首先需要安装依赖:
npm i -D @babel/plugin-transform-runtime @babel/runtime-corejs2
然后修改 webpack 配置:
// www.javascriptcn.com code example
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets: ['@babel/preset-env'],
plugins: [
[
'@babel/plugin-transform-runtime',
{
corejs: 3
}
]
]
}
}
}
]
}去除多余的 polyfill
使用 @babel/preset-env 可以根据配置的目标浏览器和环境自动插入 polyfill,但是有时候这样会导致不必要的代码被打入,可以通过 corejs 选项来指定只包含需要的 polyfill 版本。
// www.javascriptcn.com code example
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets: [
[
'@babel/preset-env',
{
corejs: 3,
useBuiltIns: 'usage',
targets: {
browsers: ['last 2 versions', 'ie >= 9']
}
}
]
]
}
}
}
]
}按需引入组件
在使用一些 UI 库时,由于组件非常丰富,如果全部引入会导致打包后的文件特别大。因此,可以使用 babel-plugin-import 缩减代码体积,将按需加载和引用组件。
npm i -D babel-plugin-import
// www.javascriptcn.com code example
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets: [
[
'@babel/preset-env',
{
corejs: 3,
useBuiltIns: 'usage',
targets: {
browsers: ['last 2 versions', 'ie >= 9']
}
}
]
],
plugins: [
[
'import',
{
libraryName: 'xxx',
libraryDirectory: 'es',
style: true
},
'xxx'
]
]
}
}
}
]
}结语
babel-loader 是非常重要的前端构建工具,通过以上的高级配置可以优化构建速度和代码体积,帮助我们更好的应对并兼容各种浏览器环境,提升开发效率和用户体验。
参考代码:webpack-babel-loader-demo。
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/67d67a84a941bf7134c3fc94