Typescript ประกาศโมดูลของบุคคลที่สามในเครื่อง
ฉันกำลังสร้างโปรเจกต์ TypeScript และใช้ไลบรารีที่ไม่ใช่ TypeScript ที่ชื่อว่า 'draggabilly';
ดังนั้นฉันกำลังพยายามประกาศมันด้วยตัวเอง
นี่คือโครงสร้างของไฟล์:
├── @types
│ └── draggabilly
│ └──index.d.ts
├── node_modules
├── package.json
├── README.md
├── src
│ ├── index.ts
│ └── application.ts
└── tsconfig.json
src/application.ts
import * as Draggabilly from 'draggabilly';
new Draggabilly('#dragItem', {
// options...
});
......
มันกำลังแสดงว่า
ไม่สามารถหาคู่มือลงประกาศสำหรับโมดูล 'draggabilly' ได้ '/node_modules/draggabilly/draggabilly.js' มีชนิดเป็น 'any' โดยอัตโนมัติ
ดังนั้นฉันจึงพยายามสร้างไฟล์ประกาศท้องถิ่น: @types/draggabilly/index.d.ts:
export as namespace draggabilly;
export = Draggabilly;
declare class Draggabilly {
constructor(selector: string, options: any);
}
จากนั้นให้รวมประเภทเส้นทางใน tsconfig.json:
{
"compilerOptions": {
......
"typeRoots": [
"./node_modules/@types",
"./@types"
]
}
}
แต่ข้อผิดพลาดยังคงอยู่ ดังนั้นฉันจึงอยากรู้ว่ามีอะไรผิดพลาดที่นี่และวิธีที่ถูกต้องในการสร้างไฟล์ประกาศโมดูลของบุคคลที่สามในเครื่อง
ฉันสร้างพื้นที่เก็บตัวอย่างสำหรับคำถามนี้บน GitHub: https://github.com/ZheFeng/test-ts-types
ปัญหาไม่ได้เกี่ยวกับแค่เรากำหนดภายในไฟล์ .d.ts อย่างไรเท่านั้น แต่ TypeScript ยังไม่สามารถหไฟล์ประกาศได้เลย
คำตอบ #1
ปัญหาอยู่ที่บรรทัด export=Draggabilly; -- คุณต้องใช้ไวยากรณ์เฉพาะของ TypeScript import let=require("module") เพื่อ import มัน:
จากเอกสารประกอบของ TypeScript:
เมื่อทำการนำเข้าโมดูลโดยใช้ export =, ต้องใช้
import let=require("module")แบบเฉพาะของ TypeScript เพื่อทำการนำเข้าโมดูลนั้น
ดังนั้นการนำเข้าของคุณควรเป็น:
import Draggabilly=require("draggabilly");
หากคุณต้องการใช้การ import แบบสไตล์ ES6 คุณสามารถแก้ไข
index.d.ts ของคุณดังนี้:export as namespace draggabilly;
export class Draggabilly {
constructor(selector: string, options: any);
}
...และนำเข้าแบบนี้:
import * as draggabilly from 'draggabilly';
new draggabilly.Draggabilly('#dragItem', {
// options...
});
คำตอบ #2
เมื่อให้ไฟล์ประกาศสำหรับโมดูลของบุคคลที่สามที่ไม่ได้ใช้ TypeScript, declare module ต้องอยู่ในขอบเขตทั่วโลก และห้ามมี import หรือ export นอก declare module
@types/draggabilly/index.d.ts
declare module "draggabilly" {
// import other libraries, optional
// ...
class Draggabilly {
constructor(selector: string, options: any);
}
export = Draggabilly;
}
src/application.ts
import Draggabilly = require("draggabilly");
new Draggabilly("#dragItem", {
// options...
});
