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

Vue3+Vite+TS项目刷新页面出现Unexpected token 'export'语法错误

Vite构建Vue+TS项目时导出类型引发浏览器语法错误

问题场景

使用Vite v5.1.3搭建的Vue v3.4.19 + TypeScript v5.3.3项目中,编写了如下TS代码:

import { ContentPiece, ContentCategory } from "internal-library";

export interface ContentCategoryWithContentPieces extends ContentCategory {
  contentPieces: Array<ContentPiece>;
}

构建后的开发包代码被转换为:

export type ContentCategoryWithContentPieces = ContentCategory & {
  contentPieces: Array<ContentPiece>;
};

刷新页面后,Chrome开发者工具抛出错误:
SyntaxError: Unexpected token 'export' (at ContentCategoryUtils.ts:7:1)

该错误由Vue Router v4.2.5触发,伴随提示:[Vue Router warn]: 路由导航期间发生未捕获错误

原因分析

浏览器原生不支持ES模块中的export type语法,而TypeScript编译时将interface转成类型别名并保留了export type导出,导致浏览器无法识别该语法。通常这是因为Vite对类型文件的处理配置不当,或者依赖包internal-library的模块配置存在问题。

解决方案

  • 检查internal-library的模块配置:如果是本地私有包,确保其package.json中type字段设为module,且types字段正确指向类型声明文件,让Vite能正确识别其类型与运行时代码的边界。
  • 调整TS编译配置:在项目tsconfig.json中启用isolatedModules,配合preserveValueImports确保类型导出被正确处理:
    {
      "compilerOptions": {
        "isolatedModules": true,
        "preserveValueImports": true
      }
    }
    
  • 优化Vite依赖预构建:在vite.config.ts中将internal-library加入预构建列表,确保Vite提前处理该依赖的类型与代码:
    import { defineConfig } from 'vite';
    import vue from '@vitejs/plugin-vue';
    
    export default defineConfig({
      plugins: [vue()],
      optimizeDeps: {
        include: ['internal-library']
      }
    });
    
  • 迁移类型至声明文件:如果该接口仅用于TS类型标注,不涉及运行时逻辑,将其移至.d.ts声明文件中。Vite会自动忽略这类文件的编译,仅保留类型信息供TS检查使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 15:46:16