将js文件加载到打字稿文件中 [英] Load js file into typescript file

查看:30
本文介绍了将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();

这篇关于将js文件加载到打字稿文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆