TypeScript变量与接口导入导出报错及正确实现方法
TypeScript接口与变量导入导出的正确实现及报错解决
问题场景
拥有3_enumerable.ts文件,尝试导出InventoryItem接口和inventoryItems变量供其他TS文件使用,原实现采用module.exports导出,编译后在浏览器中出现以下报错:
Uncaught ReferenceError: module is not defined at 3_enumerable.js:73:1Uncaught SyntaxError: Cannot use import statement outside a module (at 4_functions.js:3:1)
正确实现与解决步骤
1. 改用TypeScript ES模块导出语法
TypeScript推荐使用ES模块的export语法,替代CommonJS的module.exports,修改3_enumerable.ts的导出部分:
enum InventoryItemType { Computer = 'Computer', Furniture = 'Furniture' } interface InventoryItem { displayName: string; trackingNumber: string | number; furnitureType: InventoryItemType; cost: number; createDate?: Date; } const inventoryItems: InventoryItem[] = [ {displayName: 'item1', trackingNumber: '1234', furnitureType: InventoryItemType.Computer, cost: 10, createDate: new Date('2020-01-01')}, {displayName: 'item2', trackingNumber: '5678', furnitureType: InventoryItemType.Computer, cost: 30}, {displayName: 'item3', trackingNumber: 9101, furnitureType: InventoryItemType.Computer, cost: 30} ] // ES模块导出语法 export { InventoryItem, inventoryItems }; // 若需要使用枚举,可一并导出:export { InventoryItemType };
2. 配置tsconfig.json编译选项
确保TypeScript编译输出为ES模块,而非CommonJS,创建或修改tsconfig.json:
{ "compilerOptions": { "target": "ES6", // 目标版本至少为ES6,支持模块语法 "module": "ESNext", // 输出ES模块格式 "outDir": "./build", // 指定编译后文件输出目录 "strict": true, // 可选,开启严格类型检查 "esModuleInterop": true // 可选,兼容CommonJS模块导入 }, "include": ["*.ts"] // 指定需要编译的TS文件范围 }
3. 修正导入路径(从源TS文件导入)
在4_functions.ts中,直接从源TS文件导入,而非编译后的JS文件,TypeScript会自动处理编译和模块关联:
// 根据实际文件结构调整相对路径 import { InventoryItem, inventoryItems } from './3_enumerable';
4. 浏览器中启用模块模式
如果在浏览器环境运行代码,需在HTML的<script>标签添加type="module"属性,告知浏览器这是ES模块:
<script type="module" src="./build/4_functions.js"></script>
报错原因解析
module is not defined:浏览器不支持CommonJS的module对象,原代码编译为CommonJS格式,导致浏览器无法识别。Cannot use import statement outside a module:浏览器默认将脚本视为普通脚本,需通过type="module"声明为ES模块才能使用import语法。
内容的提问来源于stack exchange,提问作者NewToJS
相关产品推荐
相关产品推荐

