typescript 除非在每个文件中都引用,否则在 TS 文件中找不到名称“$”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41168683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot find name '$' in TS file unless referenced in every file
提问by stanggt3
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?
我正在 Visual Studio 2015 中设置打字稿。我将在 TS 文件中使用 jquery。当我使用 jquery 时,VS 会在 '$' 下划线并说找不到名称,并且不会成功构建。它构建的唯一方法是在每个 TS 文件中添加对 jquery 类型的引用。/// <reference path="typings/index.d.ts" />
无论如何要全局使用此引用而不是将其添加到每个文件中?
In Visual Studio Code I dont have this issue.
在 Visual Studio Code 中我没有这个问题。
My directory looks like this -Scripts --ts ---typings ---main.ts tsconfig.json --js
我的目录看起来像这样 -Scripts --ts ---typings ---main.ts tsconfig.json --js
My tasks.json file in the root
我在根目录下的 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 in Scripts/ts
脚本/ts 中的 taskconfig.json
{
"compileOnSave": true,
"compilerOptions": {
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "es5",
"outDir": "../lib/"
},
"exclude": [
"typings/*"
]
}
回答by lenny
In TypeScript 2.x you should install the typings like this:
在 TypeScript 2.x 中,您应该像这样安装类型:
npm install --save @types/jquery
npm install --save @types/jquery
And then:
接着:
import * as $ from "jquery";
import * as $ from "jquery";
No need to reference it, TypeScript will handle it automatically.
不需要引用它,TypeScript 会自动处理它。
回答by Roque Orts
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";
在使用 npm 的 TypeScript 3 中:
npm install --save-dev @types/jquery
和 :
import "jquery";
别名不是必需的。
如果你不使用 npm:
添加一个新的声明 (jquery.d.ts) 文件,其中包含
declare module 'jquery';
和 :
import "jquery";
回答by AlexGH
add to your tsconfig.json:
添加到您的 tsconfig.json:
"moduleResolution": "node",
"lib": [ "es2015", "es2017", "dom" ]