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

TypeScript编译为JavaScript后浏览器运行报错的问题求助

Fixing "require is not defined" and ES Module Errors in Browser TypeScript Projects

Let's break down the problem and fix it step by step:

Why You're Seeing These Errors

  • require is not defined: CommonJS modules (the output from "module": "commonjs" in tsconfig) rely on Node.js-specific APIs like require and exports — browsers don't support these natively.
  • Cannot use import statement outside a module: When you manually switched to import/export, browsers treat the script as a regular non-module file by default, which doesn't allow ES module syntax.

Step 1: Update tsconfig.json to Compile ES Modules

Change your TypeScript configuration to output ES modules instead of CommonJS, and clean up invalid settings:

{
  "compilerOptions": {
    "module": "ESNext", // Use ES module syntax (ES6/ES2015 works too)
    "target": "ES6", // Target a version of JS that supports modules
    "sourceMap": true,
    "outDir": "js",
    "moduleDetection": "force",
    "moduleResolution": "NodeNext" // Helps resolve module paths correctly
  },
  "include": ["*.ts"] // Optional: Explicitly list files to compile
  // Remove the invalid "type": "module" line — this belongs in package.json, not tsconfig
}

Step 2: Configure Your HTML to Use ES Modules

Update your index.html to tell the browser that your script is an ES module by adding type="module" to the script tag. Also, remove the useless const exports = {}; line — it won't fix the module issue:

<!DOCTYPE html>
<html lang="en">
<!-- Your existing head content -->
<body>
  <script type="module" src="js/index.js"></script>
</body>
</html>

Step 3: Fix Import Paths for Browser Compatibility

Browsers require full file extensions in ES module imports. Update your index.ts to include the .js suffix in the import (TypeScript will preserve this in the compiled output):

import {LinkedList} from "./linked_list.js"; // Add .js suffix here
class LinkedListStack{
  // Your class implementation
}

Verify the Fix

  1. Recompile your TypeScript files with tsc
  2. Open your index.html in the browser — the errors should be gone!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 16:25:18