【问题标题】:How do I import other TypeScript files?如何导入其他 TypeScript 文件?
【发布时间】:2012-10-07 11:00:58
【问题描述】:

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

文件 1:

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

文件 2:

//what goes here?

class bar extends moo.foo
{
}

【问题讨论】:

    标签: typescript


    【解决方案1】:

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

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

    【讨论】:

    • 这很好,但是,当我将代码编译为 js 时。没有“要求”或任何指向外部文件的链接...从我在其他示例中看到的内容来看,我应该执行“import moo = module("moo"); 但是,它确实抱怨有当前范围内没有moo
    • 是的,reference 不会生成任何在编译后加载该 js 的 js 代码。它仅适用于编译器。我没有使用 TypeScript 和 AMD 的经验,因为我只是捆绑了生成的 js 文件,所以我需要的一切都在那里。但我知道您需要什么,您可以在此处阅读更多相关信息:typescriptlang.org/Content/… 第 75 页(第 9 章)。顺便说一句,值得阅读整个规范,与其他语言相比,它相对较短。
    • 您可以在主 .ts 文件中使用带有 tsc 的 --all 标志。编译器根据您的引用标签找出所有依赖项,并为整个应用程序生成一个输出 .js 文件:tsc --out app.js main.ts
    • @PeterPorfy 有什么方法可以使用 T4MVC 强输入参考链接
    • 请注意,如果 TypeScript 被告知生成es2015(或esnext)模块,则在import 语句中指定文件扩展名是mandatory(除非你这样做this)。 TypeScript 不会为您添加扩展名。另外,目前无法输出.mjs,所以扩展名必须是.js
    【解决方案2】:

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

    /// <reference path='moo.ts'/>
    
    class bar extends moo.foo {
    }
    

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

    moo.ts

    export class foo {
        test: number;
    } 
    

    app.ts

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

    【讨论】:

    • 我现在完全迷失了,无论我做什么,编译器都会为每个 .ts 文件生成一个单独的 .js 并且它们中的任何一个都没有“require”代码......还有“ import moo=module("moo");" 给出一个错误,提示名称 moo 在当前范围内不存在,突出显示 module("moo") 部分
    • 这里需要澄清几点:您在 Visual Studio 中工作吗?您是否尝试直接使用 tsc 编译我在答案中给出的代码?您是否将两个文件放在同一个目录中?
    • 是的,从命令行编译,两个文件在同一个目录中。
    • 我已经分叉并向你发送了一个拉取请求。请让我知道这是否有效。
    • 完美 :) 其他人阅读:模块也需要导出,“export module xxx”
    【解决方案3】:

    如果您希望使用模块并希望将其编译为单个 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

    ///<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/

    【讨论】:

      【解决方案4】:

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

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

      多个导出

      Foo.ts

      export class Foo {}
      export interface IFoo {}
      

      Bar.ts

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

      单次导出

      Foo.ts

      class Foo
      {}
      
      export = Foo;
      

      Bar.ts

      import Foo = require("Foo");
      
      var foo = new Foo();
      

      【讨论】:

      • 我喜欢上面的方法,并且发现 tsc.exe 在对 define() 的初始调用中生成了正确的依赖关系,这太棒了!对我来说问题是 2 个单独的类,每个在自己的文件中,每个都包含在一个导出模块中 - 我可以执行“导入”,一个可以使用另一个,但是 A 类可以从 B 继承,仍然使用 TypeScript 扩展不知何故?
      • @SamuelMeacham,当然,我不明白为什么不这样做。如果您仍然遇到问题,请在此处提出新问题并链接到该问题。我去看看。
      • 这让我明白了,现在一切都超级顺利。依赖关系,继承,所有这些:stackoverflow.com/questions/21179144/…
      • @SamuelMeacham 你指的是这个页面还是你提供的链接,因为 Drew 的这个答案似乎就在...
      • 这个答案已经过时了(2014)。当前语法在 TypeScript 手册的 Modules 部分中进行了描述。
      【解决方案5】:

      使用了 "///&lt;reference path="web.ts" /&gt; 之类的引用 然后在VS2013项目属性中构建"app.ts","Typescript Build"->"Combine javascript output into file:"(checked)->"app.js"

      【讨论】:

        【解决方案6】:

        我现在会避免使用/// &lt;reference path='moo.ts'/&gt;but 用于定义文件未包含在包中的外部库。

        reference path 解决了编辑器中的错误,但这并不意味着需要导入文件。因此,如果您使用的是 gulp 工作流或 JSPM,它们可能会尝试将每个文件而不是 tsc -out 单独编译到一个文件中。

        来自 Typescript 1.5

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

        aLib.ts

        {
        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 个选项,首先您再次选择您想要的(一个接一个)

        另一个文件.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();
        }
        

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

        【讨论】:

        • 我错过了导入类型周围的花括号,所以这一行为我修复了它:import {AClass} from "./aLib.ts";
        【解决方案7】:

        由于 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

        【讨论】:

        【解决方案8】:
        import {className} from 'filePath';
        

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

        【讨论】:

        【解决方案9】:

        Visual Studio 中的快速简单处理

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

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

        【讨论】:

          【解决方案10】:

          如果你在为 web 做一些事情你需要使用 js 文件扩展名:

          import { moo } from 'file.js';
          


          如果您正在为 nodejs 做某事,我认为不要使用 js 文件扩展名:

          import { moo } from 'file';
          

          【讨论】:

          • 谢谢,但我在 8 年前问过这个问题。我现在已经解决了 ;-)
          猜你喜欢
          • 1970-01-01
          • 2021-10-04
          • 2022-01-22
          • 2016-08-19
          相关资源
          最近更新 更多