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 likerequireandexports— browsers don't support these natively.Cannot use import statement outside a module: When you manually switched toimport/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
- Recompile your TypeScript files with
tsc - Open your
index.htmlin the browser — the errors should be gone!
内容的提问来源于stack exchange,提问作者3kShoter
相关产品推荐
相关产品推荐

