我在努力
$(function(){
alert('Hello');
});
在Visual Studio中显示此错误:(TS)无法找到名称“$”..我如何使用jQuery与TypeScript ?
我在努力
$(function(){
alert('Hello');
});
在Visual Studio中显示此错误:(TS)无法找到名称“$”..我如何使用jQuery与TypeScript ?
当前回答
你可以通过扩展窗口接口来声明全局变量:
import jQuery from '@types/jquery';
declare global {
interface Window {
jQuery: typeof jQuery;
$: typeof jQuery;
}
}
来源:
https://stackoverflow.com/a/12709880/4642023 https://mariusschulz.com/blog/declaring-global-variables-in-typescript#augmenting-the-window-interface
其他回答
2019年更新:
大卫的回答更准确。
Typescript支持第三方供应商库,这些库不使用Typescript进行库开发,使用DefinitelyTyped Repo。
你需要在你的组件中声明jquery/$,如果这些类型的类型检查tsLint是On的。
如。
declare var jquery: any;
declare var $: any;
对于Angular CLI V2+
npm install jquery --save
npm install @types/jquery --save
确保jquery在angular中有一个条目。Json ->脚本
...
"scripts": [
"node_modules/jquery/dist/jquery.min.js"
]
...
转到tsconfig.app.json,在“类型”中添加一个条目
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"types": ["jquery","bootstrap","signalr"]
},
"exclude": [
"test.ts",
"**/*.spec.ts"
]
}
你可以通过扩展窗口接口来声明全局变量:
import jQuery from '@types/jquery';
declare global {
interface Window {
jQuery: typeof jQuery;
$: typeof jQuery;
}
}
来源:
https://stackoverflow.com/a/12709880/4642023 https://mariusschulz.com/blog/declaring-global-variables-in-typescript#augmenting-the-window-interface
从现在到现在,在Angular版本9,这对我来说都是有效的
通过npm安装:npm i @types/jquery只需添加——save到全局设置。 转到tsconfig.app.json,在数组“types”中添加jquery。 发球完毕。
对于Visual Studio代码
对我来说有用的是确保我通过index.html中的< script >标记来加载标准的JQuery库。
Run
npm install --save @types/jquery
现在JQuery $函数在所有.ts文件中都可用,不需要任何其他导入。