Vue3+TypeScript项目报TS1192模块无默认导出错误如何解决?
报错诱因
- TypeScript版本不兼容:当前使用的2.8.3版本为2018年发布的旧版本,Vue3最低要求TypeScript版本为4.0+,旧版本无法识别Vue3通过defineComponent导出的组件类型,也无法正确处理.vue单文件组件的默认导出规则。
- 编译配置不完整:仅开启allowSyntheticDefaultImports无法完全解决ESM和CommonJS模块的导入导出兼容问题,需要同步开启esModuleInterop配置项才能生效。
- 缺少.vue模块类型声明:项目没有配置对应的类型声明文件告诉TypeScript如何处理.vue后缀的模块,导致TS将.vue文件识别为无默认导出的普通模块。
修复方案
- 升级TypeScript到符合Vue3要求的版本,推荐安装4.9.x的LTS版本:
执行命令:npm install typescript@4.9 --save-dev - 完善tsconfig.json的compilerOptions配置,补充esModuleInterop项:
"compilerOptions": { "outDir": "dist", "removeComments": true, "lib": ["DOM", "ES2020", "ES2020.Promise"], "module": "es2020", "target": "es2015", "allowJs": true, "jsx": "preserve", "moduleResolution": "node", "allowSyntheticDefaultImports": true, "esModuleInterop": true } - 在项目根目录新增类型声明文件
shims-vue.d.ts,写入如下内容声明.vue模块的导出规则:declare module '*.vue' { import type { DefineComponent } from 'vue' const component: DefineComponent<Record<string, unknown>, Record<string, unknown>, any> export default component } - 确认.vue组件的导入语法为默认导入格式,不要使用命名空间导入:
正确写法:import SectionTitle from './components/SectionTitle.vue'
错误写法:import * as SectionTitle from './components/SectionTitle.vue'
内容的提问来源于stack exchange,提问作者mariam_gvikvarxar
相关产品推荐
相关产品推荐

