简体   繁体   English

TypeScript:有没有摆脱“导入”的方法?

[英]TypeScript: is there a way to get rid of 'import'?

I am a TypeScript beginner and I am doing some project with TypeScript + Angular 1. 我是一名TypeScript初学者,并且正在使用TypeScript + Angular 1做一些项目。

So far, I have some services defined, each with the following structure: 到目前为止,我已经定义了一些服务,每个服务都具有以下结构:

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


module SomeModule {

export class SomeService {
    constructor(...) {
    ...
    }
}

var app = AppModule.getModule();
app.service("SomeService", SomeService);
}

where my App.ts is: 我的App.ts在哪里:

module AppModule{
  'use strict';
   angular.module('SomeApp', [...]);

   export var getModule:() => ng.IModule = () => {
    return angular.module('SomeApp');
   };
}

And whenever I am trying to reference service that has a different module name, I need to include: 每当我尝试引用具有不同模块名称的服务时,都需要包括:

import SomeService = SomeModule.SomeService;

My question comes to: is there a way to omit those imports? 我的问题是:是否可以忽略这些进口? Or store them in one file, so that I can later only reference one file instead of referencing all of the services which have different modules? 还是将它们存储在一个文件中,以便以后我只能引用一个文件,而不是引用所有具有不同模块的服务?

Thanks! 谢谢!

There a few things wrong with your code. 您的代码有些错误。 The first one is that you should use <references> comments only yo reference type definition files *.d.ts not actual source files *.ts . 第一个是您应该仅使用<references>注释, *.d.ts不是引用类型定义文件*.d.ts而不是实际的源文件*.ts

The second is that your are mixing internal and external modules and you should never do that . 第二个原因是您在混合内部和外部模块, 因此绝对不要这样做

So you can use internal modules using the namespace keyword. 因此,您可以使用namespace关键字使用内部模块。 Try to avoid using the module keyword because it is the legacy version of `namespace. 尽量避免使用module关键字,因为它是命名空间的旧版本。 The following is a basic example: 以下是一个基本示例:

// some_module.ts
namespace AppModule.SomeModule {

    export class SomeService {
        constructor() {
         // ...
        }
    }
}

// app.ts
namespace AppModule {
   angular.module('SomeApp', []);

   export function getModule() {
       return angular.module('SomeApp');
   }
}

var app = AppModule.getModule();
app.service("SomeService", AppModule.SomeModule.SomeService);

With external modules the same code would look as follows: 对于外部模块,相同的代码如下所示:

// some_module.ts
class SomeService {
    constructor() {
        // ...
    }
}
export default SomeService;

// app.ts
angular.module('SomeApp', []);

function getModule() {
    return angular.module('SomeApp');
}
export default getModule;


// main.ts
import getModule from "./app";
import SomeService from "./some_module";

var app = getModule();
app.service("SomeService", SomeService);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM