Jexah
Jexah

Reputation: 183

How to import external modules inside of a loop in TypeScript?

I am trying to import "ui" inside of the loop (for dynamic loading based off of _moduleList. This works fine:

var _moduleList: Array<string>;
_moduleList.push("mdlGame");
import _tmp = require("ui");
for (var _i: number = 0; _i < _moduleList.length; ++_i) {

}

Whereas this displays a red squiggly line underneath import, saying "Unexpected token; 'statement' expected.":

var _moduleList: Array<string>;
_moduleList.push("mdlGame");
for (var _i: number = 0; _i < _moduleList.length; ++_i) {
    import _tmp = require("ui");
}

Does import not count as a statement? What is going on here, and is there a way I can work around it?

Upvotes: 7

Views: 5432

Answers (2)

aercolino
aercolino

Reputation: 2356

Time went by but OP's problem feature persists.

However, I just found a partial workaround (using the namespace import pattern), like in this example.

I was importing an index.ts file, written like this:

    import { A } from './some/a';
    import { B } from './some/other/b';
    export { A, B };                     // you'll save this list
    export const LIST: any[] = [ A, B ]; // and this other too

Saving those two lists was my purpose, because they were long tens of items each and kept growing.

  • modules.ts

    export { A } from './some/a';
    export { B } from './some/other/b';
    
  • list.ts

    import * as modules from './modules';
    export const LIST: any[] = Object.keys(modules).map(key => modules[key]);
    
  • index.ts

    export * from './modules';
    export * from './list';
    

All works as expected and it's totally DRY.

Upvotes: 8

basarat
basarat

Reputation: 275987

You can only use the import keyword at the root level of your file, e.g.:

declare module"ui"{}

//  Bad 
{
    import foo = require("ui");
}

// okay 
import bar = require("ui");

If you really really want it you can fall back to basic JS :

declare module"ui"{}
declare var require; 

//  okay now 
{
    var foo = require("ui");
}

but then you lose typesafety between the two files

Upvotes: 4

Related Questions