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
相关产品推荐
相关产品推荐

