How to use Namespace Typescript properly with Webpack
You should not be using namespaces and modules at the same time, even if you were not using webpack you would have the same problem
a normal approach with modules is to just export the class directly:
// src/App/Core/Http/Test.ts
export class Test {
public attr:any;
}
// src/App/Bootstrap.ts
import { Test } from "./Core/Http/Test";
let testInstance = new Test();
the other example:
// src/App/Bootstrap.ts
import { Test} from "./Core/Http/Test";
import { Test2 } from "./Core/Http/Test2";
let testInstance = new Test(),
test2Instance = new Test2();
hope this helps :)
I learnt that it is not possible to use namespace using webpack. Why ? Because each .ts file are considered as a module with its own scope.
Module developement is required.
I've found a solution to get my file call clearer using module instead of namespace.
In my case, I have App/Core which contains Http, Service, Factory, Provider... folders. At the root of Core folder I created a index.ts file which export all my needed files with module architecture. Let's see.
// src/App/Core/index.ts
export module Http {
export { Test } from "src/App/Core/Http/Test";
export { Test2 } from "src/App/Core/Http/Test2";
export { Test3 } from "src/App/Core/Http/Test3";
}
export module Service {
export { ServiceTest } from "src/App/Core/Service/ServiceTest";
export { ServiceTest2 } from "src/App/Core/Service/ServiceTest2";
export { ServiceTest3 } from "src/App/Core/Service/ServiceTest3";
}
//src/App/Core/index.ts ----> EOF
And in another file call import the module with the alias Core.
// src/App/Bootstrap.ts
import { * as Core } from "./Core";
let TestInstance = new Core.Http.Test(),
Test2Instance = new Core.Http.Test2(),
TestInstance = new Core.Http.Test3();
let ServiceTestInstance = new Core.Service.Test(),
ServiceTest2Instance = new Core.Service.Test2(),
ServiceTestInstance = new Core.Service.Test3();
// src/App/Bootstrap.ts ----> EOF
In TypeScript you can alias namespaces with another kind of import statement. It's pretty simple.
import { App } from "./Core/Http/Test";
import Test = App.Core.Http.Test;
import { App as App2 } from "./Core/Http/Test2";
import Test2 = App2.Core.Http.Test2;
At runtime, this is no different than const Test2 = App2.Core.Http.Test2;
but at compile-time, using an import
statement brings over all the type information, too.