
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规则是关键。
以上就是如何通过调整Rollup和Babel配置来正确转译node_modules中的特定代码?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1504111.html
微信扫一扫
支付宝扫一扫