Rollup打包TypeScript模块出现ReferenceError: _default未定义问题求助
解决Rollup打包TypeScript项目时的
ReferenceError: _default is not defined错误 核心问题分析
- package.json的main字段配置错误:你把
main指向了TypeScript声明文件./dist/index.d.ts,但运行时需要的是编译后的JavaScript文件,而非类型声明文件。 - Rollup多入口配置与期望导出逻辑不匹配:当前Rollup配置是多入口打包(Wordpress.tsx和ContactForm7.tsx),会在dist生成两个独立的JS文件,但你的
index.d.ts声明了一个包含两个模块方法的默认导出,却没有对应的JavaScript实现,导致运行时找不到_default。 - 模块格式冲突:package.json里
type: module表示项目使用ES模块,但Rollup输出格式是cjs(CommonJS),二者存在兼容问题。
具体修复步骤
1. 修正package.json配置
修改main指向编译后的JS入口,同时单独指定类型声明文件路径,并统一模块格式:
{ "main": "./dist/index.js", "types": "./dist/index.d.ts", "type": "commonjs" // 和Rollup输出格式保持一致,避免冲突 }
2. 创建统一入口并调整Rollup配置
如果期望把两个模块的方法统一导出到一个文件,需要先创建入口文件:
- 在
src目录新建index.tsx:
import { getPage } from './Wordpress'; import { sendForm } from './ContactForm7'; export default { getPage, sendForm };
- 修改
rollup.config.js为单入口打包:
import typescript from '@rollup/plugin-typescript'; import replace from 'rollup-plugin-replace'; export default { input: 'src/index.tsx', output: { file: 'dist/index.js', format: 'cjs', }, plugins: [ typescript({ tsconfig: 'tsconfig.json' }), replace({ 'process.env.MY_VARIABLE': JSON.stringify(process.env.MY_VARIABLE) }), ], external: ['react'], };
3. 重新执行打包
npm run build
验证修复
打包完成后,dist目录会生成index.js和对应的index.d.ts,此时导入模块时就能正确识别默认导出的对象,不会再出现_default is not defined错误。
内容的提问来源于stack exchange,提问作者Paul
相关产品推荐
相关产品推荐

