Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 647
Jexah Avatar asked Oct 10 '13 02:10

Jexah


People also ask

How do I import a custom module in TypeScript?

The export = syntax specifies a single object that is exported from the module. This can be a class, interface, namespace, function, or enum. When exporting a module using export = , TypeScript-specific import module = require("module") must be used to import the module.

How do I import all modules into a directory in TypeScript?

To import all modules from a directory in TypeScript, we can create a module that reexports all modules that were imported. export { default as A } from "./a"; export { default as B } from "./b"; to import the default exports from modules a and b .

How do I import items into TypeScript?

Use import myFunction from "./myModule" to bring it in. More commonly, TypeScript modules say export myFunction in which case myFunction will be one of the properties on the exported object. Use import { myFunction } from "./myModule" to bring it in.


1 Answers

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.

like image 165
aercolino Avatar answered Oct 01 '22 14:10

aercolino