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

Rollup使用node-polyfills时import与require引入模块行为差异问题

问题描述
// 该写法可正常运行
const homedir = require('os').homedir;
console.log(homedir())

// 该写法会抛出错误:"Error: 'homedir' is not exported by polyfill-node.os.js ..."
import {homedir} from 'os'
console.log(homedir())

上述代码中,使用require CommonJS写法引入os模块的homedir方法可正常运行,使用ES Module具名引入homedir的写法会抛出导出不存在的错误。核心疑问:既然import语法可同时引用ESM与CJS模块,为何二者行为存在差异?

相关Rollup配置
export default (async ()=>({

  input: 'app/svelte.ts',

  output: {
    sourcemap: !production,
    format: 'iife', // 用于在script标签中加载JS
    file: 'public/build/bundle.js',
  },

  plugins: [
    
    nodePolyfills(),
    
    svelte({
      preprocess: preprocess()
    }),

    commonjs({
      defaultIsModuleExports: true,
      transformMixedEsModules: true
    }),
    
    css({output: 'bundle.css'}),

    typescript(),

    alias({
      entries: [
        {find: /^@pkg\/(.*)/, replacement: 'packages/$1'},
      ],
    }),

    resolve({
      browser: true,
      dedupe: ['svelte'],
    }),

    !production && serve(),

    !production && livereload('public'),

    json(),
    
  ],

}))()
已验证现象

经测试,Rollup插件执行顺序会影响报错表现:

  • 若将nodePolyfills()插件调整至resolve()插件之后,报错会变更为Use output.globals to specify browser global variable names corresponding to external modules os (guessing 'os')
  • 目前已尝试按照报错提示配置externals、output.globals等参数,均未解决问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 00:45:49