简体   繁体   中英

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.

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:

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 .

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. Try to avoid using the module keyword because it is the legacy version of `namespace. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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