[英]How to import JQuery into a Typescript file?
不需要進口。 相反,我需要添加對文件頂部的引用。 所以我的 WebAPI.js 的第一行應該是/// <reference path ="../typings/jquery/jquery.d.ts"/>
而不是import { $ } from '../jquery-3.1.1';
我正在嘗試導入 jQuery 以在 Typescript 文件中使用,但我嘗試的所有操作都收到了各種錯誤。 我遵循了這里和這里的解決方案,但沒有任何運氣。
{
"compilerOptions": {
"removeComments": true,
"preserveConstEnums": true,
"out": "Scripts/CCSEQ.Library.js",
"module": "amd",
"sourceMap": true,
"target": "es5",
"allowJs": true
}
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 * 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';
根據DefinitelyTyped wiki:
TypeScript 聲明文件是在外部第三方 JavaScript 庫中定義類型、函數和參數的方式。 通過在您的 TypeScript 代碼中使用聲明文件,將啟用 Intellisense 並針對您正在使用的外部庫進行類型檢查。
jquery.d.ts
是 GitHub 上DefinitelyTyped 庫的一部分。 Definitely Typed 可以通過 NuGet 包管理器包含在 Visual Studio 項目中。
這樣做:在使用 npm 安裝 jquery 或使用 cdn 之后
第一的:
npm install @types/jquery --save-dev
之后:
從'jquery'導入*作為$;
導入很簡單:
import * as $ from 'jquery';
但前提是我們安裝相關.d.ts
文件:
npm install @types/jquery --save-dev
與上面相同,但如果您希望能夠將“ $
”用作函數,以偵聽文檔就緒事件(如“ $(function () {... })
”),請繼續閱讀。
首先,在tsconfig.json
文件中,執行如下操作:
{
"compilerOptions": {
"esModuleInterop": true
}
}
然后不帶“ * as
”部分導入,例如:
import $ from 'jquery';
Tim 使用參考編譯器指令的解決方案有效,但現在有更簡單的方法。
在 tsconfig.json 中,如果你設置了 typeRoots,你根本不需要在你的 .ts 文件中做任何事情。 TypeScript 為您完成工作。
它是如何工作的?
在我的解決方案中,我通過 npm 引入了我所有的@types,所以它們被放置在./node_modules/@types。 我也有一些我在 ./@types 上手工創建的類型。
在我的 tsconfig.json 中,我添加了:
"compilerOptions": {
// lots of other config here
"typeRoots": [
"./node_modules/@types",
"./@types"
]
}
現在我所有的類型都被編譯器自動發現和使用,所以不需要為引用標簽煩惱!
綜上所述...
我應該注意,如果您這樣做並嘗試顯式導入 jquery,它將失敗,並且您會感到困惑。 我當然是。
嘗試用 declare let $: any; 替換你的導入
在 visual studio 社區中,為了完成工作,我必須在 head / script 部分的 html 中添加 jquery,然后在 jquery script 部分下添加我的 app.ts,然后在我的 typescript 源中添加對 jquery lib 的引用。
在 html 頁面中,head 部分:
<script src="./Scripts/jquery-3.5.1.js"></script>
<script src="app.js"></script>
在 app.ts 中,ts 腳本的第一行:
/// <reference path ="./Scripts/typings/jquery/jquery.d.ts"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.