You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级Babel后rollup打包报错Plugin/Preset files仅允许导出函数

问题解决方案

报错根因

该报错是Babel 7版本的兼容性问题:Babel 7要求所有插件和预设必须导出函数,而你当前项目中混用了Babel 6时代的旧依赖,这些旧包导出的是对象,不符合新版本要求。直接导致报错的两个依赖是:

  • babel-preset-stage-2:Babel 6的stage预设,Babel 7已经废弃了所有babel-preset-stage-X系列包
  • babel-plugin-external-helpers:Babel 6的工具插件,Babel 7中已重构为@babel/plugin-external-helpers,更推荐使用@babel/plugin-transform-runtime替代

修复步骤

1. 卸载不兼容的旧依赖

执行以下命令移除冲突包:

npm uninstall babel-preset-stage-2 babel-plugin-external-helpers rollup-plugin-uglify uglify-es

额外移除的rollup-plugin-uglify和uglify-es已经停止维护,不支持ES6+语法压缩,后续会用替代方案。

2. 安装新的兼容依赖

如果需要原stage-2预设包含的语法特性,安装对应Babel 7版本的插件即可,同时安装替代uglify的压缩工具:

# 按需添加你需要的stage特性插件,以下是常用的stage-2对应插件示例
npm install @babel/plugin-proposal-class-properties @babel/plugin-proposal-decorators rollup-plugin-terser -D
# 如果需要抽离公共babel helpers,可以额外安装
npm install @babel/plugin-transform-runtime -D
npm install @babel/runtime -S

3. 修改rollup.config.js配置

调整babel配置部分,移除旧预设和插件,替换压缩工具:

import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import babel from 'rollup-plugin-babel'
// 替换为新的压缩工具
import {terser} from 'rollup-plugin-terser'
import fs from 'fs'
const pkg = JSON.parse(fs.readFileSync('./package.json'))

export default {
    name: '*********',
    input: 'src/********.js',
    output: [
        {format: 'es', file: pkg.module},
        {format: 'cjs', file: pkg.main},
        {format: 'umd', file: pkg['umd:main']}
    ],
    plugins: [
    resolve(),
    commonjs(),
    babel({
        babelrc: false,
        exclude: 'node_modules/**',
        presets: [
        [
            '@babel/preset-env',
            {
            modules: false,
            loose: true,
            targets: {browsers: ['last 2 versions', '> 1%']}
            }
        ],
        '@babel/preset-react'
        // 移除旧的babel-preset-stage-2
        ],
        plugins: [
          // 移除旧的external-helpers,按需添加新插件,示例如下:
          ['@babel/plugin-proposal-decorators', {legacy: true}],
          ['@babel/plugin-proposal-class-properties', {loose: true}]
          // 如果安装了transform-runtime,添加如下配置
          // ['@babel/plugin-transform-runtime']
        ]
    }),
    // 替换为terser
    terser()
    ]
}

4. 重新构建

清除缓存后重新安装依赖并构建:

rm -rf node_modules package-lock.json
npm install
npm run build

内容的提问来源于stack exchange,提问作者Amaarockz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 16:06:03