programing

JQuery를 Typescript 파일로 가져오려면 어떻게 해야 합니까?

showcode 2023. 4. 5. 22:27
반응형

JQuery를 Typescript 파일로 가져오려면 어떻게 해야 합니까?

갱신하다

Import는 필요 없습니다.대신 파일 맨 위에 참조를 추가해야 했습니다.그래서 제 WebAPI.js의 첫 줄은/// <reference path ="../typings/jquery/jquery.d.ts"/>대신import { $ } from '../jquery-3.1.1';


typescript 파일에서 사용하기 위해 jQuery를 Import하려고 하는데 시도 시마다 다양한 오류가 발생합니다.해결책을 따라 이곳저곳을 돌아다녔지만, 아무런 운이 없었습니다.

tsconfig.json

{
    "compilerOptions": {
        "removeComments": true,
        "preserveConstEnums": true,
    "out": "Scripts/CCSEQ.Library.js",
    "module": "amd",
        "sourceMap": true,
    "target": "es5",
    "allowJs": true
}

WebAPI.js

import { $ } from '../jquery-3.1.1';

export class ExpenseTransaction extends APIBase {

    constructor() {
        super();
    }

    Get(): void {
        let expenses: Array<Model.ExpenseTransaction>;
        let self = this;
        $.ajax({
            url: this.Connection,
            type: "GET",
            contentType: "application/json",
            dataType: "json",
            success: function (data: any): void {
                expenses = self.ConvertToEntity(data.value);
            },
            error: function (data: any): void { console.log(data.status); }
        });
    };
}

나도 해봤어import * as $ from '../jquery.3.1.1'

에러

  • Module jquery-3.1.1 has no exported member $
  • Property ajax does not exist on type (selector: any, context: any) => any

로 Import해야 합니다.import * as $ from "jquery";typescript의 매뉴얼jquery의 정의 파일에 따라 모듈은 앰비언트 모듈로 정의됩니다.

declare module "jquery" {
    export = $;
}

에 따르면:

환경 선언은 컴파일러와 함께 하는 약속입니다.런타임에 존재하지 않고 사용하려고 하면 경고 없이 파손됩니다.

가져오기는 필요하지 않습니다.대신 파일 맨 위에 Typescript 정의 파일에 참조를 추가하십시오.그래서 첫 번째 행은WebAPI.js그래야 한다

/// <reference path ="../typings/jquery/jquery.d.ts"/> 

대신

import { $ } from '../jquery-3.1.1';

확실히」에 따라서입력된 wiki:

TypeScript 선언 파일은 외부 서드파티 JavaScript 라이브러리의 유형, 함수 및 파라미터를 정의하는 방법입니다.TypeScript 코드에 선언 파일을 사용하면 Intellissense 및 사용 중인 외부 라이브러리에 대한 형식 확인이 활성화됩니다.

jquery.d.ts의 일부입니다.GitHub에서 형식 라이브러리를 찾았습니다.NuGet Package Manager를 통해 Visual Studio 프로젝트에 확실히 입력되었습니다.

npm을 사용하여 jquery를 설치하거나 cdn을 사용하여 jquery를 설치한 후 다음을 수행합니다.

첫 번째:

npm install @types/jquery --save-dev

그 후:

*를 'jquery'에서 달러로 Import한다.

es5

Import는 다음과 같이 간단합니다.

import * as $ from 'jquery';

다만, 관련하는 인스톨을 실시하는 경우만,.d.ts파일:

npm install @types/jquery --save-dev

es6

위와 같습니다만, 「」를 사용할 수 있는 경우는,$「기능으로서 문서 준비 이벤트(「」등)를 수신합니다.$(function () { ... })" )을 클릭합니다.

일단은tsconfig.json파일, 다음과 같은 작업을 수행합니다.

{
    "compilerOptions": {
        "esModuleInterop": true
    }
}

그런 다음 " 없이 Import합니다.* as " 부품, 예를 들어:

import $ from 'jquery';

stackoverflow.com/Understanding-esModuleInterop 도 참조해 주세요.

참조 컴파일러 디렉티브를 사용한 Tim의 솔루션은 기능하지만 지금은 더 쉬운 방법이 있습니다.

tsconfig.json에서 typeRoots를 설정하면 .ts 파일에서 아무것도 수행할 필요가 없습니다.TypeScript가 작업을 대신합니다.

어떻게 작동합니까?

솔루션에서는 npm을 통해 모든 @type을 가져옵니다.그러면 ./node_modules/@type에 배치됩니다../@types에서 수작업으로 작성한 타입도 몇 개 있습니다.

tsconfig.json에 다음과 같이 추가했습니다.

 "compilerOptions": {     
   // lots of other config here
   "typeRoots": [
     "./node_modules/@types",
     "./@types"
   ]
  }

모든 타입이 컴파일러에 의해 자동으로 검출되어 사용되므로 참조 태그에 신경 쓸 필요가 없습니다!

결론적으로...

이렇게 해서 jquery를 명시적으로 Import하려고 하면 실패하고 혼란스러워집니다.난 분명히 그랬다.

Import를 declaret $ : any로 대체해 보십시오.

비주얼 스튜디오 커뮤니티에서 작업을 수행하려면 헤드 / 스크립트 섹션에 html로 jquery를 추가하고 jquery 스크립트 섹션 바로 아래에 app.ts를 추가한 후 타이프 스크립트 소스의 jquery lib에 대한 참조를 추가해야 합니다.

html 페이지의 머리부분:

<script src="./Scripts/jquery-3.5.1.js"></script>
<script src="app.js"></script>

app.ts 스크립트의 첫 번째 줄:

/// <reference path ="./Scripts/typings/jquery/jquery.d.ts"/>

언급URL : https://stackoverflow.com/questions/43783307/how-to-import-jquery-into-a-typescript-file

반응형