typescript 打字稿错误:TS2304:找不到名称“$”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44796612/
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
typescript error: TS2304: Cannot find name '$'
提问by user1934212
The statement
该声明
x = $('#msgBox_' + scope.boxId).position().left;
generates an
产生一个
error TS2304: Cannot find name '$'
错误 TS2304:找不到名称“$”
although jqueryand @typesare installed in the node_modules folder.
虽然jquery和@types安装在 node_modules 文件夹中。
My tsconfig.json looks like that:
我的 tsconfig.json 看起来像这样:
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"sourceMap": true,
"moduleResolution": "node",
"declaration": true
},
"exclude": [
"node_modules"
]
}
How can I fix that?
我该如何解决?
回答by George Pasquali
Did you try to :
您是否尝试过:
import $ = require('jquery');
at the 1 line? This should work. Though you should have a deeper look into es6 modules and ts modules to get a grip on how you could take advantage of the es6 modular system. Also d.ts files...
在第 1 行?这应该有效。尽管您应该更深入地了解 es6 模块和 ts 模块,以了解如何利用 es6 模块化系统。还有 d.ts 文件...
This should be helpful: https://www.typescriptlang.org/docs/handbook/modules.html
这应该会有所帮助:https: //www.typescriptlang.org/docs/handbook/modules.html
回答by user1934212
Turns out I was missing the "@types/jquery" node module, which contains a definition of "$". Once I added "@types/jquery": "^3.2.5" to the list of "devDependencies" in my package.json and reinstalled via "npm install", everything worked fine.
结果我错过了“@types/jquery”节点模块,它包含一个“$”的定义。一旦我将 "@types/jquery": "^3.2.5" 添加到我的 package.json 中的 "devDependencies" 列表并通过 "npm install" 重新安装,一切正常。
回答by Brant
If AngularCLI is where your injecting JQuery, then in your controller/component, you can declare the variable like so:
如果 AngularCLI 是您注入 JQuery 的地方,那么在您的控制器/组件中,您可以像这样声明变量:
declare var $: any;
回答by Steffi Keran Rani J
One reason for this kind of error is your node_modulesdoesn't contain the type definitions for jquery ie. the package @types/jqueryis missing.
这种错误的一个原因是您的node_modules不包含 jquery 的类型定义,即。包裹@types/jquery不见了。
My workaround is as follows:
我的解决方法如下:
Open the command prompt in the root of your project folder and type:
npm install --save @types/jquery.If you are posed with a question to choose the version, choose the latest one.
Once the above command ends successfully, run
yarn install.Once the above install is success, run
yarn startto start your project.
在项目文件夹的根目录中打开命令提示符并键入:
npm install --save @types/jquery.如果您遇到选择版本的问题,请选择最新版本。
上述命令成功结束后,运行
yarn install.上述安装成功后,运行
yarn start以启动您的项目。

