如何确保Babel在使用Rollup打包时正确转译node_modules中的代码?

如何确保Babel在使用Rollup打包时正确转译node_modules中的代码?

Rollup打包时Babel转译node_modules代码的正确方法

使用Rollup构建项目时,正确配置Babel以转译node_modules中的代码至关重要。本文将分析一个实际案例,并提供解决方案,帮助您避免Babel转译失败的情况。

问题:Babel未能转译node_modules中的ES特性

假设您希望使用Babel转译@xyflow包中使用的空值合并运算符(??)。您的rollup.config.mjs和babel.config.json配置如下:

rollup.config.mjs:

babel({   extensions: ['.js', '.jsx', '.mjs'],   presets: ['@babel/preset-env'],   babelHelpers: 'runtime',   include: ['src/**/*', 'node_modules/@xyflow/**/*'], }),

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"]   ] }

尽管babel.config.json中已包含@babel/plugin-proposal-nullish-coalescing-operator插件,但打包后的代码仍然包含??运算符,说明Babel未能正确转译@xyflow包。

解决方案:改进include配置

问题在于rollup.config.mjs中include选项的匹配规则不够精确。 ‘node_modules/@xyflow/**/*’ 仅匹配node_modules/@xyflow目录下的所有文件,但可能无法涵盖所有需要转译的文件。

更可靠的解决方案是使用正则表达式

include: ['src/**/*', /node_modules/((?:.*[/])?@xyflow(?:[/].*)?)/],

此正则表达式可以匹配node_modules目录下所有@xyflow相关的文件路径,确保Babel能够正确转译所有需要的代码。 修改后的include配置解决了??运算符未能转译的问题。

结论

在使用Rollup和Babel进行项目构建时,务必仔细检查include或exclude选项的配置,确保其能够准确匹配需要转译或排除的文件路径。 正确的路径匹配是成功转译node_modules中代码的关键。 使用正则表达式可以提供更灵活和精确的匹配能力。

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享