Rollup打包时,Babel转译node_modules中特定代码的技巧
前端项目打包过程中,Rollup负责模块处理,Babel负责代码转译。然而,Babel有时无法正确处理node_modules中的特定包。本文将介绍如何解决此问题。
问题:Babel未能转译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"] ] }
版本信息:
"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",
解决方案:改进include规则
问题在于include规则的匹配不够精准。 原始配置无法完全匹配@xyflow包下的所有文件。
改进后的include配置:
include: ['src/**/*', /node_modules/((?:.*[/])?@xyflow(?:[/].*)?)/],
使用正则表达式更灵活地匹配node_modules/@xyflow目录下的所有文件,从而确保Babel正确转译@xyflow包中的代码,解决??运算符未转译的问题。
通过此案例,我们了解到Rollup和Babel配置的细节至关重要,尤其是在处理node_modules中的特定包时,精确的include规则是关键。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END