如何使用Rollup和Babel正确转译node_modules中的@xyflow包代码?

如何使用Rollup和Babel正确转译node_modules中的@xyflow包代码?

正确配置Rollup和Babel转译node_modules中的代码

使用Rollup打包时,处理node_modules中的依赖包代码至关重要。本文将解决一个实际案例:如何正确配置Rollup和Babel来转译@xyflow包中的代码,避免?? (nullish coalescing operator)等现代语法在打包后未被转译的问题。

初始配置中,Rollup的rollup.config.mjs文件中的Babel配置如下:

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

问题在于include选项的匹配规则。’node_modules/@xyflow/**/*’ 仅匹配node_modules目录下直接位于@xyflow文件夹中的文件,而忽略了@xyflow包内部的子目录结构。

解决方案是将include配置修改为使用正则表达式,以更灵活地匹配@xyflow包及其子目录下的所有文件:

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

此正则表达式能够匹配node_modules目录下所有包含@xyflow路径的文件。通过这个调整,Babel能够正确识别并转译@xyflow包中的所有代码,从而解决??语法未被转译的问题。 最终确保打包后的代码兼容目标环境 (例如IE11)。 使用的Rollup和Babel版本如下:

  • “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”

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