如何解决VS Code中‘declare var jQuery:any;’的报错问题?
Let’s break down exactly what’s causing this back-and-forth error and how to fix it properly:
The Root Cause
Your initial error (cannot redeclare block-scoped variable 'jQuery') happened because you manually added declare var jQuery: any; while TypeScript was already loading jQuery’s official type definitions (probably from the @types/jquery package). When you deleted that manual declaration, TypeScript lost any reference to jQuery’s type information entirely—hence the TS2304 compile error.
Step-by-Step Solutions
Option 1: Use Official Type Definitions (Recommended)
This is the cleanest approach if you’re using npm/yarn to manage dependencies:
- First, make sure you have both jQuery and its type definitions installed:
npm install jquery @types/jquery --save # Or if you use Yarn: yarn add jquery @types/jquery - Update your
tsconfig.jsonto tell TypeScript to load jQuery’s global types. Add"jquery"to thetypesarray undercompilerOptions:{ "compilerOptions": { // ... other existing config "types": ["jquery"] } } - Now you can use
jQueryor$anywhere in your code without manual declarations—no more conflicts, no more compile errors.
Option 2: Manual Declaration for CDN-Loaded jQuery
If you’re loading jQuery via a CDN instead of npm, you need a single, global declaration file (not scattered in components):
- Create a new file in your
srcfolder namedtypings.d.ts(or any.d.tsfile—TypeScript automatically picks these up). - Add the following declarations to it:
declare var jQuery: any; declare var $: any; // Include this if you use the $ shorthand too - Double-check your
tsconfig.jsonincludes this file. If yourincludearray has"src/**/*", it will already be picked up. If not, add it explicitly:
This ensures the declaration is loaded once globally, avoiding duplicate declaration errors while keeping TypeScript aware of{ "include": ["src/**/*", "src/typings.d.ts"] }jQuery.
Option 3: Module-Specific Import
If you prefer not to use global jQuery, import it only in the components that need it:
- Install jQuery and its types (same as Option 1).
- In
app.config.tsandpages.component.ts, add the import at the top:
This way, you don’t need any global declarations, and TypeScript will recognize the variable in those files.import * as jQuery from 'jquery'; // Or if you prefer the $ shorthand: import * as $ from 'jquery';
Why This Works
- The duplicate declaration error came from having two sources of
jQuerytype info (your manual declare +@types/jquery). - The TS2304 error happened because removing your manual declare left TypeScript with no knowledge of what
jQueryis. - By centralizing the type info (either via official types or a single
.d.tsfile), you eliminate both issues.
内容的提问来源于stack exchange,提问作者tony09uk

