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