【发布时间】:2017-04-26 06:49:30
【问题描述】:
假设我有一个 foo.js 文件,我在其中声明了一个变量、一个函数和一个类。
它还没有在项目中。
现在假设我想在 home.ts 方法中使用这个变量、类和函数,或者只是让它全局可用(在 home.ts 方法中使用)。
我怎样才能做到这一点?
【问题讨论】:
标签: javascript angular typescript ionic2 faye
假设我有一个 foo.js 文件,我在其中声明了一个变量、一个函数和一个类。
它还没有在项目中。
现在假设我想在 home.ts 方法中使用这个变量、类和函数,或者只是让它全局可用(在 home.ts 方法中使用)。
我怎样才能做到这一点?
【问题讨论】:
标签: javascript angular typescript ionic2 faye
让我们在你的 foo.ts 文件中说我们有一个函数
myfunt(){
//your logic goes here
}
现在如果你想在 home.ts 文件中使用这个函数
step1:将你的 foo.ts 文件导入 home.ts
step2:在你的导出类中应该是这样的
export class home extends foo {
//since you have used extends keyword now you unlocked all the data in foo.ts file for home.ts file
//here now try to access your myfunt() funtion
constructor(){
super.myfunt(); //user super keyword to access all the data available in foo.ts file
}
}
【讨论】:
您可以使用定义文件 (.d.ts)。
首先,检查 foo.js 是否已经有社区创建的定义文件。在这里检查: http://microsoft.github.io/TypeSearch/ 或者这里https://github.com/DefinitelyTyped/DefinitelyTyped
如果存在,你可以这样安装:
npm install --save @types/foo
如果没有,您可以为此 javascript 文件创建自己的定义文件。
我们称之为 foo.d.ts,内容如下:
declare var data:any;
declare function myFunc(n:string);
一旦拥有它,您就可以像使用普通的“.ts”文件一样使用它。
import * as foo from "./foo"; //"./foo" is the path of your .d.ts.
foo.myFunc()
更多信息在这里: https://blogs.msdn.microsoft.com/typescript/2016/06/15/the-future-of-declaration-files/
【讨论】:
foo 我现在从 foo.d.ts 文件中导入?我试试看
import * as foo from "./foo" ;如果你是通过 npm 安装的,你可以像 import * as foo from "foo"; 一样导入它。