I'm trying to figure some things related to ES6 modules. How to use namespaces together with angular and typescript.
Assume the following code represents an angular directive. Does anyone know what the module
keyword mean and how can you access MyClass in other file.
// file1.ts
module NSpace.Space {
export class MyClass {
constructor() { ... }
...
}
}
I have tried accessing on another file using and re-exporting, however
// file2.ts
import {MyClass} from 'file1';
export {MyClass}
I get this error: error TS2306: File 'file.ts' is not a module
My questions are:
module
keyword?module Space.Space1.Space2 ...
From what I've read and experienced so far it seems that ES6 modules are defined based on file structure, that's why I get this error.
I have not written this code, that's why I'm asking. Also it might be useful to mention that I'm using System.JS for importing.
The module
keyword in TypeScript caused a bit of confusion, so it is going to be renamed namespace
.
Rather than use namespaces, though, you can organise your code by files / file system (which means the actual file location will match the perceived namespace. This is how "exteral modules" (TypeScript) work - and also how ECMAScript 2015 modules work.
So with a quick adjustment, you'll have:
// file1.ts
export class MyClass {
constructor() { ... }
...
}
And then this will work:
import {MyClass} from 'file1';
If you compile targeting ES6, you'll notice that this line of code needs no translation, it matches the standard for module imports. If you target ES5 or lower, TypeScript will transform this statement for you (you can choose the transformation using the --module
flag.
I tend to use the UMD compilation option, which means the output will work in web browsers (with RequireJS) or on Node. System JS is actually gaining a lot of traction currently, so you may want to consider that too. Eventually, browsers will simply natively support module loading.