在打字稿中引用 javascript 文件 [英] Reference javascript file inside typescript

查看:31
本文介绍了在打字稿中引用 javascript 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在打字稿文件中使用 javascript 函数.如何在打字稿文件中引用包含该函数的 javascript 文件?

I would like to use a javascript function inside a typescript file. How can I reference the javascript file containing that function inside typescript file?

我试过了

<reference path="../libs/myjsfile.js" />

这会在构建时出现错误,例如:无法解析引用的文件:../libs/myjsfile.js

this brings an error while building like: Cannot resolve referenced file: ../libs/myjsfile.js

推荐答案

虽然上述两个答案适用于小型或单变量 API,但正确的答案是为您的 JavaScript 文件编写类型声明文件.

While the two answers above will work for a small or single variable API, the correct answer is to write a type declaration file for your JavaScript file.

示例的类型声明文件将命名为 myjsfile.d.ts,其中 .d.ts 后缀告诉 TypeScript 编译器它正在解析声明文件.如果你使用 Visual Studio,你的声明文件将被 TypeScript 编译器识别,只要它在你正在处理的项目中的某个地方(任何地方).

The type declaration file for your example would be named myjsfile.d.ts, where the .d.ts suffix is what tells the TypeScript compiler that it's parsing a declaration file. If you use Visual Studio, your declaration file will be recognized by the TypeScript compiler as long as it is somewhere (anywhere) in the project you are working on.

声明文件存储有关 JavaScript 变量、函数和对象的元数据,以便 TypeScript 编译器可以完成其工作.如果您的 JavaScript 文件恰好是常用的库或框架,DefinitelyTyped 绝对是您找到所需定义文件的地方.

Declaration files store metadata about JavaScript variables, functions and objects so the TypeScript compiler can do its job. If your JavaScript file happens to be a library or framework in common use, DefinitelyTyped is definitely the place to find the definition file you need.

如果您的 JavaScript 是您自己的作品或鲜为人知,则您必须编写自己的类型声明文件.请参阅TypeScript 手册中的编写 .d.ts 文件部分一>.

If your JavaScript is your own work or less well known, you'll have to write your own type declaration file. See the section Writing .d.ts files in The TypeScript Handbook.

如果名称声明文件听起来令人生畏,请不要担心 - 它们比程序更容易编写.另外,请记住,您不需要为 JavaScript 文件指定所有元数据,只需指定您需要的功能即可.

If the name declaration file sounds intimidating, don't worry - they are far easier to write than programs. Also, remember that you don't need to specify all metadata for your JavaScript file, just the functionality you need.

如果您需要任何帮助,请告诉我!

Let me know if you need any help!

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

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