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

使用Rollup打包浏览器端memfs包出现exports is not defined错误

问题根因

这个报错是因为memfs及其依赖是纯CommonJS规范编写的模块,Rollup将其转换为ESM格式输出时,没有正确为老版本CommonJS代码注入全局exports/module变量的兼容逻辑,导致浏览器ESM环境下找不到全局exports变量。

解决方案

你遗漏了CommonJS转换的动态目标配置和ESM兼容规则,按以下方式修改配置即可解决:

  • 调整@rollup/plugin-commonjs的转换配置,开启混合模块转换、指定memfs相关模块为动态引入目标,确保所有CommonJS语法被正确转换
  • 在output配置中添加interop规则,兼容CommonJS模块的导出逻辑
  • 如果是浏览器直接引用打包产物,可优先选择iife格式输出,兼容性更好

修改后的完整rollup.config.js如下:

import resolve from "@rollup/plugin-node-resolve"
import commonjs from "@rollup/plugin-commonjs"
import nodePolyfills from "rollup-plugin-polyfill-node";

export default {
    input: 'index.js',
    output: {
        dir: "dist",
        format: 'esm', // 如果是浏览器直接引用可改为'iife',同时添加name参数指定全局变量名
        interop: 'auto', // 自动处理CommonJS和ESM的导出兼容
        exports: 'named' // 统一导出规则,避免默认导出冲突
    },
    plugins:[
        nodePolyfills(),
        resolve({
            preferBuiltins: false,
            browser: true,
        }),
        commonjs({
            transformMixedEsModules: true, // 允许转换同时含有ESM和CommonJS语法的模块
            include: /node_modules/,
            dynamicRequireTargets: [
                // 指定memfs及其依赖路径,强制转换动态require逻辑
                'node_modules/memfs/**/*.js',
                'node_modules/fs-monkey/**/*.js'
            ],
            esmExternals: false, // 不将CommonJS依赖视为ESM模块
        }),
    ],
}

如果保留esm格式输出,在HTML中引用打包产物时,必须给script标签添加type="module"属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 21:36:05