18

I'm setting up typescript in Visual Studio 2015. I'm going to be using jquery with the TS files. When I use jquery, VS will underline the '$' and say cannot find name, and will not build successfully. The only way it will build is if I add the reference to jquery typings in each TS file. /// <reference path="typings/index.d.ts" /> Is there anyway to use this reference globally instead of adding it to every file?

In Visual Studio Code I dont have this issue.

My directory looks like this -Scripts --ts ---typings ---main.ts tsconfig.json --js

My tasks.json file in the root

    {
    "version": "0.1.0",

    // The command is tsc. Assumes that tsc has been installed using npm install -g typescript
    "command": "tsc",

    // The command is a shell script
    "isShellCommand": true,

    // Show the output window only if unrecognized errors occur.
    "showOutput": "silent",

    // Tell the tsc compiler to use the tsconfig.json from the open folder.
    "args": ["-p", "../Scripts/Weblink/ts"],

    // use the standard tsc problem matcher to find compile problems
    // in the output.
    "problemMatcher": "$tsc"
}

taskconfig.json in Scripts/ts

{
"compileOnSave": true,
"compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "outDir": "../lib/"
},
"exclude": [
    "typings/*"
]
}
stanggt3
  • 183
  • 1
  • 1
  • 5

3 Answers3

33

In TypeScript 2.x you should install the typings like this:

npm install --save @types/jquery

And then:

import * as $ from "jquery";

No need to reference it, TypeScript will handle it automatically.

More info

lenny
  • 2,978
  • 4
  • 23
  • 39
  • And any plugins should be [added to a typings](https://medium.com/@NetanelBasal/typescript-integrate-jquery-plugin-in-your-project-e28c6887d8dc) file, so the compiler merges these signatures in the known jquery typings interface. – Benny Bottema Jan 04 '18 at 21:23
  • 1
    I'm currently refactoring a code with a lot of `declare const $: any`. Is there any impact on performances, size of the bundle, ... or anything else I can't imagine if replace those by `import * as $ from "jquery"` ? – Sylvain Jul 18 '18 at 19:18
1
  • In TypeScript 3 using npm:

    npm install --save-dev @types/jquery

    And :

    import "jquery";

    Alias is not necessary.

  • If you don't use npm:

    Add a new declaration (jquery.d.ts) file containing declare module 'jquery';

    And :

    import "jquery";

Roque Orts
  • 310
  • 2
  • 11
0

add to your tsconfig.json:

"moduleResolution": "node",
"lib": [ "es2015", "es2017", "dom" ]
AlexGH
  • 2,735
  • 5
  • 43
  • 76