将js文件加载到打字稿文件中

将js文件加载到打字稿文件中

问题描述:

我有一个简单的 TypeScript (ts),它需要一个来自 JavaScript 文件的函数.如何将该js文件导入ts文件?我是否必须为该 js 文件创建一个 ts 文件才能在我的 ts 文件中使用它?

I have a simple TypeScript (ts) which needs a function from a JavaScript file. How can I import that js file into ts file? Do I have to create a ts file for that js file to be able to use it in my ts file?

最简单的方法就是声明你正在使用的函数:

The easiest way is to just declare the function you're using:

File1.js

function greet() { return "Hello!"; }

File2.ts

declare function greet(): string;

/* ... later ... */
var hi = greet();

如果您的场景更复杂(即多个文件引用 File1.js,或者 File1.js 中有许多函数会混淆 File2.ts),您可以创建一个 File1.d.ts 文件并从File2.ts:


If your scenario is more complex (i.e. multiple files referencing File1.js, or there are many functions in File1.js that would clutter up File2.ts), you can make a File1.d.ts file and reference that from File2.ts:

File1.d.ts

function greet(): string;

File2.ts

/// <reference path="File1.d.ts" />

/* ... later ... */
var hi = greet();