7

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?

2 Answers 2

7

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.

4

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

2
  • 1
    Thanks. Is there any way to dynamically load multiple modules at the root level?
    – Jexah
    Commented Oct 10, 2013 at 2:57
  • @Jexah unfortunately not via the import keyword
    – basarat
    Commented Oct 10, 2013 at 4:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.