找不到名字' $'在TS文件中,除非在每个文件中引用

时间:2016-12-15 16:15:39

标签: typescript visual-studio-2015

我在Visual Studio 2015中设置了打字稿。我将使用带有TS文件的jquery。当我使用jquery时,VS会强调&#39; $&#39;并说找不到名字,也不会成功建立。它构建的唯一方法是在每个TS文件中添加对jquery typings的引用。 /// <reference path="typings/index.d.ts" />无论如何全局使用此引用而不是将其添加到每个文件中?

在Visual Studio Code中,我没有这个问题。

我的目录看起来像这样 -Scripts  --ts    ---分型    --- main.ts    tsconfig.json  --js

我在tasks

中的tasks.json文件
    {
    "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 / ts

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

3 个答案:

答案 0 :(得分:31)

在TypeScript 2.x中,你应该安装这样的类型:

npm install --save @types/jquery

然后:

import * as $ from "jquery";

无需引用它,TypeScript将自动处理它。

More info

答案 1 :(得分:0)

add to your tsconfig.json:

"moduleResolution": "node",
"lib": [ "es2015", "es2017", "dom" ]

答案 2 :(得分:0)

  • 在TypeScript 3中使用npm:

    npm install --save-dev @types/jquery

    然后:

    import "jquery";

    不需要别名。

  • 如果您不使用npm:

    添加一个包含declare module 'jquery';的新声明(jquery.d.ts)

    然后:

    import "jquery";