TypeScript와 함께 jQuery를 사용하는 방법
노력하고 있습니다
$(function(){
alert('Hello');
});
Visual Studio에서이 오류를 표시합니다 (TS) Cannot find name '$'.
. TypeScript와 함께 jQuery를 어떻게 사용할 수 있습니까?
프로젝트 에 jQuery 용 TypeScript 선언 파일 을 다운로드하여 포함시켜야 할 가능성이 높습니다 jquery.d.ts
.
옵션 1 : @types 패키지 설치 (TS 2.0 이상 권장)
package.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");
당신은 컴파일해야 할 수도 있습니다 --allowSyntheticDefaultImports
-add "allowSyntheticDefaultImports": true
에서 tsconfig.json .
패키지를 설치 하시겠습니까?
jquery가 설치되어 있지 않은 경우 npm을 통해 종속성으로 설치하려고 할 수 있습니다 (그러나 항상 그런 것은 아닙니다) :
npm install --save jquery
을위한 비주얼 스튜디오 코드
나를 위해 작동하는 것은 index.html 의 <script> 태그 를 통해 표준 JQuery 라이브러리 로딩을 수행하는 것 입니다.
운영
npm install --save @types/jquery
이제 JQuery $ 함수는 다른 가져 오기없이 모든 .ts 파일에서 사용할 수 있습니다.
JQuery에 Typescript 유형이 필요할 수 있다고 생각합니다. Visual Studio를 사용한다고 말했기 때문에 Nuget을 사용하여 얻을 수 있습니다.
https://www.nuget.org/packages/jquery.TypeScript.DefinitelyTyped/
Nuget 패키지 관리자 콘솔의 명령은
Install-Package jquery.TypeScript.DefinitelyTyped
업데이트 : 의견에서 언급 했듯이이 패키지는 2016 년 이후 업데이트되지 않았습니다.하지만 https://github.com/DefinitelyTyped/DefinitelyTyped 의 Github 페이지를 방문 하여 유형을 다운로드 할 수 있습니다. 라이브러리의 폴더를 탐색 한 다음 index.d.ts
파일 을 다운로드하십시오 . 프로젝트 디렉토리의 아무 곳이나 팝업하면 VS가 즉시 사용해야합니다.
내 경우에는 이것을해야했다.
npm install @types/jquery --save-dev // install jquery type as dev dependency so TS can compile properly
npm install jquery --save // save jquery as a dependency
그런 다음 스크립트 파일에서 A.ts
import * as $ from "jquery";
... jquery code ...
이러한 유형의 유형 검사에 대해 tsLint가 켜져 있으면 구성 요소에서 jquery
/ 를 선언해야합니다 $
.
예를 들어.
declare var jquery: any;
declare var $: any;
다른 타이핑 라이브러리도 타이핑이 설치되어있는 경우에도 잘 작동합니다.
Angular CLI V7의 경우
npm install jquery --save
npm install @types/jquery --save
Make sure jquery has an entry in angular.json -> scripts
...
"scripts": [
"node_modules/jquery/dist/jquery.min.js"
]
...
Go to tsconfig.app.json and add an entry in "types"
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"types": ["jquery","bootstrap","signalr"]
},
"exclude": [
"test.ts",
"**/*.spec.ts"
]
}
If you want to use jquery in a web application (e.g. React) and jquery is already loaded with <script src="jquery-3.3.1.js"...
On the webpage you can do:
npm install --save-dev @types/query
and the use it with:
let $: JQueryStatic = (window as any)["jQuery"];
so, you don't need to load jquery a second time (with npm install --save jquery
) but have all the advantages of Typescript
This works for me:
export var jQuery: any = window["jQuery"];
Here is my TypeScript & jQuery config steps.
It makes jQuery's types support to work better than the most articles in the internet . ( I believe. )
first:
npm install jquery --save
npm install @types/jquery --save-dev
second( very very very important ! ! ! ):
import jquery = require("jquery");
// this helps TypeScript to understand jQuery best !!! otherwise It will confused .
const $: JQueryStatic = jquery;
then , You Can Enjoy It :
$(document).ready(function () {
$('btn').click(function () {
alert('I am clicked !')
}
}
It's silky smooth !!!
참고URL : https://stackoverflow.com/questions/32050645/how-to-use-jquery-with-typescript
'Programing' 카테고리의 다른 글
ggplot2의 개별 패싯에 텍스트 주석 달기 (0) | 2020.07.11 |
---|---|
게스트 컴퓨터에서 호스트 컴퓨터에 어떻게 액세스합니까? (0) | 2020.07.11 |
날짜 범위 간의 자바 스크립트 루프 (0) | 2020.07.11 |
공백을 포함하여 줄 길이별로 텍스트 파일 정렬 (0) | 2020.07.11 |
Google지도와 같은 위치 활성화 대화 상자를 표시하는 방법 (0) | 2020.07.11 |