TypeScript中添加export {}后报Unexpected token错误的原因?
解决TypeScript中“Project无法作为模块编译”及类内export语法错误问题
错误原因分析
- 类内放置
export {}的语法错误:export是TypeScript的模块级语法,只能在文件的顶层作用域使用,绝对不能放在类的内部。类的内部仅允许定义构造函数、方法、属性或访问器,所以你把export {}写在Project类里会触发“Unexpected token. 预期为构造函数、方法、访问器或属性”的语法错误。 - “无法作为模块编译”的根源:TypeScript默认将没有任何导入/导出语句的文件识别为全局脚本(Script),而非模块(Module)。脚本中的类会成为全局变量,容易引发跨文件的命名冲突,因此TS会抛出“无法作为模块编译”的提示。
正确解决方法
你有两种简洁的解决思路:
方案1:在文件顶层添加空导出
把export {}移到文件最外层,不要嵌套在类内部,这样TS就会自动将该文件识别为模块:
class Project { title: string; description: string; image: HTMLImageElement; constructor( title: string, description: string, image: HTMLImageElement ) { this.title = title; this.description = description; this.image = image; } } // 放在文件顶层,标记当前文件为模块 export {};
方案2:直接导出Project类
如果你需要在其他文件中复用这个类,直接导出它更符合模块化的设计逻辑,这样文件自然会被TS识别为模块,无需额外的空导出:
export class Project { title: string; description: string; image: HTMLImageElement; constructor( title: string, description: string, image: HTMLImageElement ) { this.title = title; this.description = description; this.image = image; } }
配置说明
这个问题不需要修改任何TypeScript配置(如tsconfig.json),只需正确使用模块级的导入/导出语法即可解决。
内容的提问来源于stack exchange,提问作者Rik
相关产品推荐
相关产品推荐

