TypeScript新手求助:如何阻止编译后生成额外的"魔法代码"?
Hey there! Let's break down what's going on here and get you that clean, module-free JavaScript output you want for local browser debugging.
First off, those extra bits of code (export {} and Object.defineProperty(exports, "__esModule", { value: true });) aren't magic—they're TypeScript treating your files as modules instead of plain browser scripts. Browsers don't understand Node.js's CommonJS module system (hence the exports is not defined error), and ES modules require HTTP/HTTPS to load (which is why file:// throws CORS errors).
Here's how to generate pure, module-free JS:
1. Tweak Your tsconfig.json
Update your compilerOptions to explicitly tell TypeScript to output plain global scripts instead of modules:
{ "compilerOptions": { "target": "ES2015", "module": "None", // This is the key—disables all module-related code generation "moduleDetection": "force", // Ensures files without import/export are treated as scripts, not modules "removeComments": false, "noImplicitAny": true, "noImplicitThis": true, "moduleResolution": "Node" // You can keep this, it won't interfere with script output } }
module: "None"tells TypeScript to skip generating any module wrapper code entirely.moduleDetection: "force"prevents TypeScript from auto-marking files as modules (which was causing that randomexport {}line even when you had no imports/exports).
2. Stick to Global Script Style
If your code has import or export statements, TypeScript will still treat it as a module. If you don't need modularity (just a script that runs globally in the browser), remove those import/export lines. If you do need modules, you'll have to use a local HTTP server (more on that below).
3. Local Server Hack for Modular Code (If You Need It)
If you want to use ES modules but hate uploading to a remote server, spin up a quick local HTTP server in seconds:
- Install
http-servervia npm:npm install -g http-server - Run it in your project folder:
http-server - Access your page at
http://localhost:8080—no more CORS errors!
Why Did Your Old Configs Fail?
- First config (no
moduleset): TypeScript defaults to using ES modules for ES2015+ targets, so it addedexport {}to mark the file as a module. - Second config (
module: "CommonJS"): This generates Node.js-style module code, which browsers don't recognize (hence theexports is not definederror).
内容的提问来源于stack exchange,提问作者bdcoder

