
前端项目打包过程中,Rollup负责模块处理,Babel负责代码转译。然而,Babel有时无法正确处理node_modules中的特定包。本文将介绍如何解决此问题。
node_modules中的特定代码假设我们使用Rollup打包,需要用Babel转译node_modules中的@xyflow包,但@xyflow包中的空值合并运算符??未能被转译。
Rollup配置文件(rollup.config.mjs)中的Babel配置如下:
babel({
extensions: ['.js', '.jsx', '.mjs'],
presets: ['@babel/preset-env'],
babelHelpers: 'runtime',
include: ['src/**/*', 'node_modules/@xyflow/**/*'],
}),Babel配置文件(babel.config.json)如下:
{
"presets": [
[
"@babel/preset-env",
{
"modules": false,
"useBuiltIns": "usage",
"corejs": "3",
"targets": {
"ie": 11
}
}
],
"@babel/preset-react"
],
"plugins": [
[
"@babel/plugin-transform-runtime",
{
"corejs": 3,
"helpers": true,
"regenerator": true,
"babelHelpers": "runtime"
}
],
["@babel/plugin-proposal-class-properties"],
["@babel/plugin-proposal-nullish-coalescing-operator"]
]
}版本信息:
<code>"rollup": "4.22.5", "@babel/core": "7.25.2", "@babel/plugin-proposal-class-properties": "7.18.6", "@babel/plugin-proposal-nullish-coalescing-operator": "7.18.6", "@babel/plugin-transform-react-jsx": "7.25.2", "@babel/plugin-transform-runtime": "7.25.4", "@babel/preset-env": "7.25.4", "@babel/preset-react": "7.24.7", "@babel/runtime-corejs3": "7.25.6",</code>
include规则问题在于include规则的匹配不够精准。 原始配置无法完全匹配@xyflow包下的所有文件。
改进后的include配置:
include: ['src/**/*', /node_modules/((?:.*[/\])?@xyflow(?:[/\].*)?)/],
使用正则表达式更灵活地匹配node_modules/@xyflow目录下的所有文件,从而确保Babel正确转译@xyflow包中的代码,解决??运算符未转译的问题。
通过此案例,我们了解到Rollup和Babel配置的细节至关重要,尤其是在处理node_modules中的特定包时,精确的include规则是关键。
以上就是如何通过调整Rollup和Babel配置来正确转译node_modules中的特定代码?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号