typescript 在打字稿中导入函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43468722/
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
Importing functions in typescript
提问by Kai
How can I reuse functions? I want to declare them once then include them in other files.
如何重用函数?我想声明它们一次,然后将它们包含在其他文件中。
I created a module Global, containing some functions which I may want to add to other typescript files
我创建了一个模块 Global,其中包含一些我可能想要添加到其他打字稿文件的功能
I tried the following in another typescript file:
我在另一个打字稿文件中尝试了以下内容:
import test = require("./Global");
import * as testFunctions from "Global"
Both lines give errors saying the module cannot be found. The module is definitely visible to typescript as I am actually referencing this module at other places in the file, calling it's functions, which is working (EXAMPLE: Global.stopSpinner()).
这两行都给出错误,说找不到模块。该模块对打字稿绝对可见,因为我实际上是在文件的其他位置引用该模块,调用它的函数,该函数正在工作(例如:Global.stopSpinner())。
Im not sure what I am doing wrong however, as I am following examples. Could someone explain me the correct way?
但是,我不确定我做错了什么,因为我正在遵循示例。有人可以向我解释正确的方法吗?
回答by Paleo
An example:
一个例子:
// global.ts
export function abc() {
}
// main.ts
import { abc } from "./global"
abc();
I suggest to read the introduction to ES6 modules from Mozilla.
我建议阅读Mozilla 对 ES6 模块的介绍。
回答by Shaymena
//This is how it should look in order to work
import * as testFunctions from "./Global";
I hope this helps!
我希望这有帮助!
回答by Dave Cousineau
One option is simply to compile your library into a .js output file (and .d.ts typescript definitions file), and then include the .js file in your projects. You don't need to use a module system then, though it can be tricky getting your .js files in the right place and properly referenced and published.
一种选择是将您的库编译为 .js 输出文件(和 .d.ts 打字稿定义文件),然后将 .js 文件包含在您的项目中。那时您不需要使用模块系统,尽管将您的 .js 文件放在正确的位置并正确引用和发布可能会很棘手。