如何导入其他 TypeScript 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12930049/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 00:54:05  来源:igfitidea点击:

How do I import other TypeScript files?

typescript

提问by Roger Johansson

When using the TypeScript plugin for vs.net, how do I make one TypeScript file import modules declared in other TypeScript files?

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

file 1:

文件1:

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

file 2:

文件2:

//what goes here?

class bar extends moo.foo
{
}

回答by Peter Porfy

From TypeScript version 1.8 you can use simple importstatements just like in ES6:

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

import { ZipCodeValidator } from "./ZipCodeValidator";

let myValidator = new ZipCodeValidator();

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

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

Old answer:From TypeScript version 1.5 you can use tsconfig.json: http://www.typescriptlang.org/docs/handbook/tsconfig-json.html

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

It completely eliminates the need of the comment style referencing.

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

Older answer:

较旧的答案:

You need to reference the file on the top of the current file.

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

You can do this like this:

你可以这样做:

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

class Foo { }

etc.

等等。

These paths are relative to the current file.

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

Your example:

你的例子:

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

class bar extends moo.foo
{
}

回答by Valentin

Typescript distinguishes two different kinds of modules: Internalmodules are used to structure your code internally. At compile-time, you have to bring internal modules into scope using reference paths:

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

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

class bar extends moo.foo {
}

On the other hand, externalmodules are used to refernence external source files that are to be loaded at runtimeusing CommonJSor AMD. In your case, to use external module loading you have to do the following:

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

moo.ts

模拟题

export class foo {
    test: number;
} 

app.ts

应用程序

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

Note the different way of brining the code into scope. With external modules, you have to use modulewith the name of the source file that contains the module definition. If you want to use AMD modules, you have to call the compiler as follows:

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

tsc --module amd app.ts

This then gets compiled to

然后将其编译为

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);
})    

回答by Drew Noakes

If you're using AMD modules, the other answers won't work in TypeScript 1.0 (the newest at the time of writing.)

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

You have different approaches available to you, depending upon how many things you wish to export from each .tsfile.

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

Multiple exports

多个出口

Foo.ts

export class Foo {}
export interface IFoo {}

Bar.ts

巴茨

import fooModule = require("Foo");

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


Single export

单一出口

Foo.ts

class Foo
{}

export = Foo;

Bar.ts

巴茨

import Foo = require("Foo");

var foo = new Foo();

回答by codeBelt

If you are looking to use modules and want it to compile to a single JavaScript file you can do the following:

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

tsc -out _compiled/main.js Main.ts

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

ClassOne.ts

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

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

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

CommonComponent.ts

通用组件.ts

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

You can read more here: http://www.codebelt.com/typescript/javascript-namespacing-with-typescript-internal-modules/

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

回答by Flavien Volken

I would avoid now using /// <reference path='moo.ts'/>but for external libraries where the definition file is not included into the package.

我现在会避免使用/// <reference path='moo.ts'/>但用于定义文件未包含在包中的外部库。

The reference pathsolves errors in the editor, but it does not really means the file needs to be imported. Therefore if you are using a gulp workflow or JSPM, those might try to compile separately each file instead of tsc -outto one file.

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

From Typescript 1.5

从打字稿 1.5

Just prefix what you want to export at the file level (root scope)

只需在文件级别(根范围)添加要导出的前缀

aLib.ts

aLib.ts

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

You can also add later in the end of the file what you want to export

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

{
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
}

Or even mix both together

或者甚至将两者混合在一起

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

For the import you have 2 options, first you pick again what you want (one by one)

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

anotherFile.ts

另一个文件.ts

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

Or the whole exports

或者整个出口

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

Note regarding the exports: exporting twice the same value will raise an error { export valueZero = 0; export {valueZero}; // valueZero is already exported… }

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

回答by Szymon Dudziak

Since TypeScript 1.8+you can use simple simple importstatement like:

由于打字稿1.8+你可以使用简单的简单import语句,如:

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

or the wildcard version:

或通配符版本:

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

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

阅读更多:https: //www.typescriptlang.org/docs/handbook/modules.html

回答by user3461121

used a reference like "///<reference path="web.ts" />and then in the VS2013 project properties for building "app.ts","Typescript Build"->"Combine javascript output into file:"(checked)->"app.js"

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

回答by Ahmed Raza

import {className} from 'filePath';

remember also. The class you are importing , that must be exported in the .ts file.

还记得。您正在导入的类,必须在 .ts 文件中导出。

回答by Mark Macneil Bikeio

Quick Easy Process in Visual Studio

Visual Studio 中的快速简单流程

Drag and Dropthe file with .ts extension from solution window to editor, it will generate inline reference code like..

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

/// <reference path="../../components/someclass.ts"/>