TypeScript项目报错TS2304:找不到名称'exports',求解决方法
解决TypeScript项目中的"Cannot find name 'exports'"错误
问题场景
我正在开发一个TypeScript项目,运行后出现错误:Address.ts:4:1 - error TS2304: Cannot find name 'exports',以下是代码快照:
Address.ts
export class Address { public Street1: string = "mywork"; } exports.Address = Address;
script.ts
import { Address } from "./Address"; class Customer { private _customerName = ""; public addressobj: Address = new Address(); public set CustomerName(name: string) { if (name.length == 0) { throw ("name is misssing"); } this._customerName = name; } public get CustomerName(): string { return this._customerName; } getFullName(): string { alert(this.addressobj.Street1); return this._customerName; } }
index.html
<html> <head> </head> <script type="module" src="src/script.js"></script> <body> <h1>hello word masum</h1> <script> try { var cs = new Customer(); cs.CustomerName = "sudia"; alert(cs.getFullName()); } catch (ex) { alert(ex); } </script> </body> </html>
错误原因
你在Address.ts中同时混用了ES模块导出语法(export class Address)和CommonJS导出语法(exports.Address = Address)。当TypeScript以ES模块模式编译时,exports变量不存在,因此抛出找不到名称的错误。
解决步骤
删除多余的CommonJS导出代码
直接移除Address.ts中的exports.Address = Address;这一行,保留ES模块的导出即可:export class Address { public Street1: string = "mywork"; }修复额外的运行时问题
解决完exports错误后,你还会遇到Customer未定义的问题,因为:script.ts中的Customer类没有导出,模块内的变量默认是私有的,无法被外部普通脚本访问。- 普通
<script>标签无法访问模块脚本(type="module")内的变量。
可以调整为以下方案:
- 在
script.ts中导出Customer类:import { Address } from "./Address"; export class Customer { // ... 原有代码不变 ... } - 修改
index.html,将访问Customer的代码放在模块脚本中:<html> <head> </head> <body> <h1>hello word masum</h1> <script type="module"> import { Customer } from "./src/script.js"; try { var cs = new Customer(); cs.CustomerName = "sudia"; alert(cs.getFullName()); } catch (ex) { alert(ex); } </script> </body> </html>
内容的提问来源于stack exchange,提问作者Gulam Samdani
相关产品推荐
相关产品推荐

