typescript 将js文件加载到打字稿文件中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13753311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Load js file into typescript file
提问by sheldon_cooper
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?
我有一个简单的 TypeScript (ts),它需要一个来自 JavaScript 文件的函数。如何将该js文件导入ts文件?我是否必须为该 js 文件创建一个 ts 文件才能在我的 ts 文件中使用它?
回答by Ryan Cavanaugh
The easiest way is to just declare
the function you're using:
最简单的方法是仅declare
使用您正在使用的函数:
File1.js
文件1.js
function greet() { return "Hello!"; }
File2.ts
文件2.ts
declare function greet(): string;
/* ... later ... */
var hi = greet();
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.js,或者 File1.js 中有许多函数会混淆 File2.ts),您可以创建一个 File1.d.ts 文件并从 File2.ts 引用该文件:
File1.d.ts
文件1.d.ts
function greet(): string;
File2.ts
文件2.ts
/// <reference path="File1.d.ts" />
/* ... later ... */
var hi = greet();
回答by Joel Cochran
Just for the archives,if you add a /// ref for a JavaScript file inside your TS file, the compiler will try to validate all the code in the JS files and throw a huge error list. Try it with jQuery or something like that and you'll see what I mean.
仅对于档案,如果您在 TS 文件中为 JavaScript 文件添加 /// ref,编译器将尝试验证 JS 文件中的所有代码并抛出一个巨大的错误列表。用 jQuery 或类似的东西试试,你就会明白我的意思。