ife*_*olz 0 javascript jquery requirejs typescript asp.net-core
我目前在我的"ts"文件的顶部有这个import $ = require("jquery");我正在这样做,因为我试图在我的打字稿文件中使用jquery,但我似乎无法让它编译,因为它返回标题中声明的错误.我正在使用ASP.NET CORE
脚本文件夹
tsonfig.json
{
"compilerOptions": {
"noImplicitAny": true,
"noEmitOnError": true,
"sourceMap": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"target": "es5",
"module": "umd"
},
"files": [
"wwwroot/js/player-page.ts",
"wwwroot/js/playerDetails-page.ts",
"wwwroot/js/DataTableSetting.ts"
],
"compileOnSave": true
}
Run Code Online (Sandbox Code Playgroud)
main.ts
require.config({
baseUrl: "wwwroot/js/lib",
paths: {
jquery: "jquery-3.1.1"
}
});
require(["jquery", "DataTable", "DataTableSetting"],
($: JQueryStatic, datatable: DataTables.DataTable, dataTableSetting: any) => {
console.log($);
});
Run Code Online (Sandbox Code Playgroud)
ASP.NET MVC布局页面
<script data-main="~/js/lib/main" src="~/js/lib/require.js"></script>
Run Code Online (Sandbox Code Playgroud)
控制台错误
http://requirejs.org/docs/errors.html#scripterror
at makeError (require.js:5)
at HTMLScriptElement.onScriptError (require.js:5)
Run Code Online (Sandbox Code Playgroud)
TS文件
import $ = require("jquery");
import DataTables = require("./DataTableSetting");
export class Player {
private playerTable: HTMLTableElement;
constructor(playerTable: HTMLTableElement) {
this.playerTable = playerTable;
this.wireEvents(this.playerTable);
}
initDatatable(playerTable: HTMLTableElement) {
$(playerTable).DataTable();
}
private wireEvents(playerTable: HTMLTableElement): void {
const btnsUpdatePlayer = playerTable.querySelectorAll(".btnUpdatePlayer");
Array.prototype.forEach.call(btnsUpdatePlayer,
(btn: HTMLButtonElement) => {
btn.addEventListener("click", (e : Event)=> {
console.log(e.target);
}, false);
});
}
}
window.onload = () => {
var $dtPlayerTable = document.getElementById("tblPlayer");
var playerTable: HTMLTableElement = <HTMLTableElement>$dtPlayerTable;
const player = new Player(playerTable);
};
Run Code Online (Sandbox Code Playgroud)
TypeScript有两种模块:
在您的代码中,"./DataTableSetting"模块是第一种,"jquery"模块是第二种.TypeScript可以DataTableSetting通过查看文件系统并发现位于那里的文件来验证模块是否存在.
但是,对于jquery,TypeScript无法在磁盘上找到文件.所以它需要你的帮助.它需要你告诉它:" 不要担心,TypeScript,你找不到文件.我将确保这个模块在需要时实际存在,这里是它将包含的类型 ".
你告诉TypeScript模块存在的方式,即使它不在磁盘上,通过明确地声明它,如下所示:
declare module "jquery"
{
class JQueryStatic
{
...
}
...
}
Run Code Online (Sandbox Code Playgroud)
此声明是文件jquery.d.ts包含的内容.所以你实际上并不需要自己写这个声明.
但是,问题是:TypeScript编译器如何知道在哪里查找此声明?
实际上有两种方法可以指明您的声明所在的位置.
首先,您可以/// <reference>在顶部包含一个指令player-page.ts,如下所示:
/// <reference path="../DefinitelyTyped/jquery.d.ts" />
Run Code Online (Sandbox Code Playgroud)
这将有效地"包含" jquery.d.ts正文中的内容player-page.ts,从而使该模块声明对"jquery"代码可见.
其次,您可以tsconfig.json通过指定compilerOptions/typeRoots以下内容来指定查找类型定义的位置:
{
"compilerOptions": {
"typeRoots" : ["wwwroot/js/DefinitelyTyped"],
...
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3347 次 |
| 最近记录: |