TypeScript导出时如何消除'require is not defined'控制台错误
问题描述
我有一个3_enumerable.ts文件,导出了InventoryItem接口和inventoryItems常量数组。在4_functions.ts中同时导入这两个成员后,编译生成的4_functions.js里出现了require语句,导致浏览器控制台抛出Uncaught ReferenceError: require is not defined错误;但如果只导入接口,就不会生成这个require语句。我的tsconfig.json配置如下,请问怎么消除这个错误,是否需要修改配置?
3_enumerable.ts 代码
export interface InventoryItem { displayName: string; trackingNumber: string | number; furnitureType: InventoryItemType; cost: number; createDate?: Date; } export 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} ]
4_functions.ts 代码
import {InventoryItem, inventoryItems} from './3_enumerable'
编译后的 4_functions.js 代码
var _3_enumerable_1 = require("./3_enumerable");
控制台错误信息
4_functions.js:3 Uncaught ReferenceError: require is not defined at 4_functions.js:3:23
tsconfig.json 配置
{ "compilerOptions": { "target": "ES5", "outDir": "build", }, "include": ["src/**/*"] }
解决方案
原因分析
- TypeScript默认采用
CommonJS模块系统,编译后会生成require语句,但浏览器原生不支持CommonJS模块规范,因此报错。 - 仅导入接口时,TypeScript的接口属于编译时类型标识,会在编译阶段被完全擦除,不会生成实际的模块导入代码,因此不会出现
require语句,也就不会触发错误。
解决办法
有两种可行的解决路径:
1. 修改TypeScript配置为浏览器支持的模块系统
在tsconfig.json的compilerOptions中添加"module": "ESNext"(或"ES6"等浏览器兼容的模块类型),同时建议开启"moduleResolution": "bundler"以适配浏览器原生模块或打包工具:
{ "compilerOptions": { "target": "ES5", "outDir": "build", "module": "ESNext", "moduleResolution": "bundler" }, "include": ["src/**/*"] }
修改配置后,编译生成的代码会使用浏览器支持的import/export语法。同时需要在HTML中引入JS文件时添加type="module"属性:
<script type="module" src="build/4_functions.js"></script>
2. 使用打包工具(如Vite、Webpack、Rollup)
如果项目需要兼容旧浏览器,或存在较多模块依赖,推荐使用打包工具。打包工具会将所有模块打包为浏览器可识别的文件,自动处理模块导入导出的兼容问题,无需手动处理require或import的适配。
- 以Vite为例,只需初始化项目,将TS文件放入
src目录,运行vite build即可生成可直接在浏览器运行的打包文件。
内容的提问来源于stack exchange,提问作者NewToJS
相关产品推荐
相关产品推荐

