当前位置: 代码网 > it编程>编程语言>正则表达式 > 如何通过调整Rollup和Babel配置来正确转译node_modules中的特定代码?

如何通过调整Rollup和Babel配置来正确转译node_modules中的特定代码?

2025年03月30日 正则表达式 我要评论
rollup打包时,babel转译node_modules中特定代码的技巧前端项目打包过程中,rollup负责模块处理,babel负责代码转译。然而,babel有时无法正确处理node_modules

如何通过调整rollup和babel配置来正确转译node_modules中的特定代码?

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中的特定代码?的详细内容,更多请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com