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