如何让tsconfig.json的compileOnSave对.js文件生效?
Let’s walk through the exact steps to get compileOnSave working for your .js files—this is a common gotcha with TypeScript’s JS file handling in older VS versions:
1. Tweak Your tsconfig.json Settings
You already have allowJs: true and compileOnSave: true, but we need one more key setting to trigger TypeScript to process .js files on save. Update your tsconfig.json to include:
{ "compileOnSave": true, "allowJs": true, "declaration": true, // This tells TypeScript to generate .d.ts declarations from your .js files "target": "ES5", // Match your desired output JavaScript version "outDir": "./dist" // Optional but recommended to keep compiled files organized }
The declaration: true flag is critical here—TypeScript needs a clear reason to process .js files, and generating type declarations is the primary use case for compiling JS with TS.
2. Enable JavaScript Compilation in Visual Studio Project Settings
VS2015 has project-level settings that can override tsconfig for compile-on-save:
- Right-click your project in Solution Explorer → Select Properties
- Navigate to the TypeScript Build tab
- Under the General section, check the box labeled Compile JavaScript files
- Double-check that the Compile on save option at the top of the tab is also checked
3. Ensure Your .js File is Included in the Project
If you renamed main.ts to main.js manually, VS might not have added it to the project’s tracked files:
- In Solution Explorer, right-click the
Scripts/Widgetsfolder → Add → Existing Item - Select
main.jsand add it to the project. This ensures VS monitors the file for save triggers.
4. Restart Visual Studio
Older VS versions sometimes need a refresh to pick up new tsconfig and project settings. Close and reopen the IDE to make sure all changes take effect.
Quick Test
Make a small edit to main.js (e.g., change the log message to console.log("Hello, compile-on-save!");), save the file, and check your output directory. You should see an updated .js file (and a .d.ts declaration file if you enabled declaration: true) generated automatically.
内容的提问来源于stack exchange,提问作者Ed I

