如何使用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 分享