如何导入其他TypeScript文件?


164

将TypeScript插件用于vs.net时,如何制作一个在其他TypeScript文件中声明的TypeScript文件导入模块?

文件1:

module moo
{
    export class foo .....
}

文件2:

//what goes here?

class bar extends moo.foo
{
}

Answers:


202

从TypeScript 1.8版开始,您可以import像在ES6中一样使用简单的语句:

import { ZipCodeValidator } from "./ZipCodeValidator";

let myValidator = new ZipCodeValidator();

https://www.typescriptlang.org/docs/handbook/modules.html

旧答案:从TypeScript 1.5版开始,您可以使用tsconfig.jsonhttp : //www.typescriptlang.org/docs/handbook/tsconfig-json.html

它完全消除了注释样式引用的需要。

较旧的答案:

您需要在当前文件的顶部引用该文件。

您可以这样做:

/// <reference path="../typings/jquery.d.ts"/>
/// <reference path="components/someclass.ts"/>

class Foo { }

等等

这些路径是相对于当前文件的。

你的例子:

/// <reference path="moo.ts"/>

class bar extends moo.foo
{
}

1
但是,当我将代码编译为js时,这可以正常工作。没有“ require”或到外部文件的任何链接...从其他示例中可以看到,我应该做一个“ import moo = module(“ moo”);但是,它确实抱怨说有在目前的范围内没有麻烦
罗杰·约翰逊

2
是的,reference编译后不会生成任何加载该js的js代码。它仅用于编译器。我没有TypeScript和AMD的经验,因为我只是捆绑了生成的js文件,因此我需要的一切都在那里。但是,我看到了您的需求,您可以在此处阅读有关此内容的更多信息:typescriptlang.org/Content/…在第75页(第9章)。值得一读的是整个规范,与其他语言相比,它相对较短。
彼得·波菲

3
您可以--all在主.ts文件中将标志与tsc一起使用。编译器根据您的参考标记找出所有依赖关系,并为整个应用程序生成一个输出.js文件:tsc --out app.js main.ts
null

@PeterPorfy有什么方法可以使用T4MVC强烈键入参考链接
Mark Macneil Bikeio

请注意,如果打字稿被告知产生es2015(或esnext)模块,指定的文件扩展名import的语句是强制性的(除非你做这个)。TypeScript不会为您添加扩展名。另外,目前无法输出.mjs,因此扩展名必须为.js
Dan Dascalescu

83

Typescript区分两种不同的模块:内部模块用于内部构造代码。在编译时,您必须使用引用路径将内部模块引入作用域:

/// <reference path='moo.ts'/>

class bar extends moo.foo {
}

另一方面,外部模块用于引用要在运行时使用CommonJSAMD加载的外部源文件。对于您的情况,要使用外部模块加载,您必须执行以下操作:

o

export class foo {
    test: number;
} 

应用程序

import moo = module('moo');
class bar extends moo.foo {
  test2: number;
}

注意将代码嵌入作用域的不同方法。对于外部模块,必须使用module包含模块定义的源文件的名称。如果要使用AMD模块,则必须按以下方式调用编译器:

tsc --module amd app.ts

然后将其编译为

var __extends = this.__extends || function (d, b) {
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
}
define(["require", "exports", 'moo'], function(require, exports, __moo__) {
    var moo = __moo__;

    var bar = (function (_super) {
        __extends(bar, _super);
        function bar() {
            _super.apply(this, arguments);

        }
        return bar;
    })(moo.foo);
})    

7
我现在感觉完全迷失了,无论我做什么,编译器都会为每个.ts文件生成一个单独的.js,并且它们中的任何一个都没有“ require”代码...也“ import moo = module(“ moo” );“错误提示名称moo在当前作用域中不存在,突出显示了module(” moo“)部分
Roger Johansson 2012年

这里有几点要澄清:您在Visual Studio中工作吗?您是否尝试直接使用tsc编译我在答案中给出的代码?您是否将两个文件都放在同一目录中?
瓦伦丁

1
是的,从命令行编译,两个文件都在同一目录中。
罗杰·约翰逊

2
我已经分叉并向您发送了拉取请求。请让我知道是否可行。
瓦伦丁

12
完美的:)对于其他阅读本文的人来说:模块也需要导出,“导出模块xxx”
Roger Johansson 2012年

20

如果您使用的是AMD模块,则其他答案将在TypeScript 1.0(撰写本文时为最新版本)中不起作用。

您可以使用不同的方法,具体取决于您希望从每个.ts文件中导出多少个内容。

多次出口

export class Foo {}
export interface IFoo {}

巴特

import fooModule = require("Foo");

var foo1 = new fooModule.Foo();
var foo2: fooModule.IFoo = {};

单出口

class Foo
{}

export = Foo;

巴特

import Foo = require("Foo");

var foo = new Foo();

我喜欢上面的方法,并发现tsc.exe在对define()的初始调用中生成了正确的依赖项,这非常棒!对我来说,问题是2个单独的类,每个类都在各自的文件中,每个类都包装在导出模块中-我可以执行“导入”,并且一个可以使用另一个类,但是A类可以从B继承,仍然使用TypeScript扩展不知何故?
塞缪尔·米查姆

@SamuelMeacham,当然,我不明白为什么不这样做。如果您仍然遇到问题,请提出一个新问题并在此处链接。我会看一看。
Drew Noakes 2014年

1
这让我理清了,现在一切都变得非常顺利。相关性,继承性,这一切:stackoverflow.com/questions/21179144/...
塞缪尔·米查姆

@SamuelMeacham是要引用此页面还是您提供的链接,因为Drew的回答似乎很具体……
Alexander Mills 2014年

这个答案已经过时了(2014年)。当前的语法在TypeScript手册的“ 模块”部分中进行了描述。
Dan Dascalescu

18

如果您希望使用模块并将其编译为单个JavaScript文件,则可以执行以下操作:

tsc -out _compiled/main.js Main.ts

维护

///<reference path='AnotherNamespace/ClassOne.ts'/>
///<reference path='AnotherNamespace/ClassTwo.ts'/>

module MyNamespace
{
    import ClassOne = AnotherNamespace.ClassOne;
    import ClassTwo = AnotherNamespace.ClassTwo;

    export class Main
    {
        private _classOne:ClassOne;
        private _classTwo:ClassTwo;

        constructor()
        {
            this._classOne = new ClassOne();
            this._classTwo = new ClassTwo();
        }
    }
}

ClassOne.ts

///<reference path='CommonComponent.ts'/>

module AnotherNamespace
{
    export class ClassOne
    {
        private _component:CommonComponent;

        constructor()
        {
            this._component = new CommonComponent();
        }
    }
}

CommonComponent.ts

module AnotherNamespace
{
    export class CommonComponent
    {
        constructor()
        {
        }
    }
}

您可以在此处了解更多信息:http : //www.codebelt.com/typescript/javascript-namespacing-with-typescript-internal-modules/


11

我会避免现在使用,/// <reference path='moo.ts'/>而是将外部文件库用于不包含定义文件的外部库。

reference path编辑器解决了错误,但它并没有真正意味着文件需从国外进口。因此,如果您使用的是gulp工作流程或JSPM,则它们可能会尝试分别编译每个文件,而不是tsc -out一个文件。

从打字稿1.5开始

只需在文件级别(根作用域)添加要导出的前缀

图书馆

{
export class AClass(){} // exported i.e. will be available for import
export valueZero = 0; // will be available for import
}

您也可以稍后在文件末尾添加要导出的内容

{
class AClass(){} // not exported yet
valueZero = 0; // not exported yet
valueOne = 1; // not exported (and will not in this example)

export {AClass, valueZero} // pick the one you want to export
}

甚至混合在一起

{
class AClass(){} // not exported yet
export valueZero = 0; // will be available for import
export {AClass} // add AClass to the export list
}

对于导入,您有2个选项,首先您再次选择想要的内容(一个接一个)

anotherFile.ts

{
import {AClass} from "./aLib.ts"; // you import only AClass
var test = new AClass();
}

或整个出口

{
import * as lib from "./aLib.ts"; // you import all the exported values within a "lib" object
var test = new lib.AClass();
}

关于出口的注意事项:出口两次相同的值将引发错误{export valueZero = 0; 导出{valueZero}; // valueZero已经导出...}


我缺少导入类型周围的花括号,因此该行为我修复了该问题:import {AClass} from "./aLib.ts";
Samuel Slade 2016年

8

从TypeScript开始,1.8+您可以使用简单的简单import语句,例如:

import { ClassName } from '../relative/path/to/file';

或通配符版本:

import * as YourName from 'global-or-relative';

了解更多:https : //www.typescriptlang.org/docs/handbook/modules.html


支持全局路径
弗拉基米尔·

@VladimirVenegas我不知道是什么你究竟在寻找,但请看看这里:github.com/Microsoft/TypeScript/wiki/...
Szymon Dudziak

对于刚接触Typescript的用户,这是最佳答案。有关完整的示例,请参阅:github.com/bitjson/typescript-starter
Jason Dreyzehner,2017年

3

使用了类似的引用"///<reference path="web.ts" /> ,然后在VS2013项目属性中用于构建“ app.ts”,“ Typescript Build”->“将javascript输出合并到文件中:”(选中)->“ app.js”



-1

Visual Studio中的快速简易过程

扩展名为.ts的文件从解决方案窗口拖放到编辑器,它将生成内联参考代码,如..

/// <reference path="../../components/someclass.ts"/>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.