Typescript和JQuery编译错误:找不到名字’$’
我正在用jquery测试typescript,但是当我编译test.ts文件时,它总是给我一个错误,指出:找不到名字’$’。
我已经导入了jquery并添加了它的定义参考。 如果我在test.ts
文件中使用import $ = require("jquery")
, test.ts
在进行tsc
编译时会出现另一个错误“ Cannot find module jquery
”。 但是,JQuery文件夹已存在于node_modules文件夹中。
有谁知道在打字稿中使用jquery的正确方法是什么?
以下是我的步骤:
- 使用
npm install jquery --save
- 使用
typings install --global --save dt~jquery
和jquery定义 - 在test.ts的顶部添加jquery引用
///
tsconfig.json
{ "compilerOptions": { "jsx": "react", "outDir": "./dist", "sourceMap": true, "noImplicitAny": true, "module": "commonjs", "target": "es5", "experimentalDecorators": true }, "exclude": [ "node_modules" ], "files": [ "./typings/index.d.ts", "./src/wo/tests/test.ts", ] }
test.ts
/// let test:any=$("div");
我不知道它是否有帮助,但我为我的datepicker解决了同样的问题。
首先我用这个命令安装了jQuery: npm install --save-dev @types/jquery
然后在angular-cli.json文件中添加依赖项:
"styles": [ "../node_modules/bootstrap/dist/css/bootstrap.css", "../node_modules/font-awesome/css/font-awesome.css", "../node_modules/ng2-datetime/src/vendor/bootstrap-datepicker/bootstrap-datepicker3.min.css", "styles.css" ] "scripts": [ "../node_modules/jquery/dist/jquery.js", "../node_modules/ng2-datetime/src/vendor/bootstrap-datepicker/bootstrap-datepicker.min.js" ]
我认为添加jQuery部分可能会对你有用。 如果有效,请告诉我。
如果你发现这些错误的时间是90%,那是因为@ types / jquery的版本问题
试试跑步:
npm install jquery --save
然后在app.module.ts
:
import * as $ from 'jquery';
然后运行:
npm install @types/jquery@2.0.47
你应该准备好了。