我在努力
$(function(){
alert('Hello');
});
在Visual Studio中显示此错误:(TS)无法找到名称“$”..我如何使用jQuery与TypeScript ?
我在努力
$(function(){
alert('Hello');
});
在Visual Studio中显示此错误:(TS)无法找到名称“$”..我如何使用jQuery与TypeScript ?
当前回答
从现在到现在,在Angular版本9,这对我来说都是有效的
通过npm安装:npm i @types/jquery只需添加——save到全局设置。 转到tsconfig.app.json,在数组“types”中添加jquery。 发球完毕。
其他回答
对于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
在安装jquery和@types/jquery(作为dev依赖项)后,使用以下导入:
import * as $ from "jquery";
对我来说,只有这样才有用。 (angular9)
很可能你需要下载并包含jQuery-jquery.d的TypeScript声明文件。在你的项目里。
选项1:安装@types包(推荐用于TS 2.0+)
和你的包放在同一个文件夹里。Json文件,执行如下命令:
npm install --save-dev @types/jquery
然后编译器会自动解析jquery的定义。
选项2:手动下载(不推荐)
在这里下载。
选项3:使用类型(Pre TS 2.0)
如果你正在使用类型,那么你可以这样包括它:
// 1. Install typings
npm install typings -g
// 2. Download jquery.d.ts (run this command in the root dir of your project)
typings install dt~jquery --global --save
设置好定义文件后,在所需的TypeScript文件中导入别名($),然后像往常一样使用它。
import $ from "jquery";
// or
import $ = require("jquery");
你可能需要在tsconfig.json中使用——allowSyntheticDefaultImports - add "allowSyntheticDefaultImports": true来编译。
还要安装软件包?
如果你没有安装jquery,你可能想通过npm将它作为依赖项安装(但并不总是这样):
npm install --save jquery
步骤1。 我使用的是yarn,你可以安装jQuery & jQuery的类型下面的cmd。
yarn add jquery
yarn add @types/jquery -D
步骤2 在你的tsx文件中添加
import jquery from 'jquery';
const $: JQueryStatic = jquery;
步骤3: 你可以把jQuery添加到react组件中。
useEffect(() => {
$(() => {
console.log("Hello JQuery!");
});
}, []);