I would like to create a project using Typescript modules, however allow it to be consumed from vanilla javascript.
Lets say it contains 3 modules each containing a single class, A
, B
, and C
.
i.e.
A.ts:
export default class A {
/* things */
}
B.ts:
export default class B {
/* things */
}
C.ts:
export default class C {
/* things */
}
All of these are built and bundled into one dist.js
file with webpack. I would like the user of the library to be able to do something akin to
<script src="dist.js"></script>
<script>
var foo = new LettersLibrary.A();
</script>
how would I go about doing this, ultimately the goal is to be able to develop taking advantage of typescript modules, but provide a library usable from vanilla js.
I would like to create a project using Typescript modules, however allow it to be consumed from vanilla javascript.
Lets say it contains 3 modules each containing a single class, A
, B
, and C
.
i.e.
A.ts:
export default class A {
/* things */
}
B.ts:
export default class B {
/* things */
}
C.ts:
export default class C {
/* things */
}
All of these are built and bundled into one dist.js
file with webpack. I would like the user of the library to be able to do something akin to
<script src="dist.js"></script>
<script>
var foo = new LettersLibrary.A();
</script>
how would I go about doing this, ultimately the goal is to be able to develop taking advantage of typescript modules, but provide a library usable from vanilla js.
Share Improve this question asked Dec 14, 2017 at 13:45 L. L. BlumireL. L. Blumire 3551 gold badge2 silver badges9 bronze badges 1 |1 Answer
Reset to default 15Use a TypeScript Namespace for this. You can declare your classes inside it and then export them from inside the module. Your user will then be able to use it like you want.
https://www.typescriptlang.org/docs/handbook/namespaces.html
Example:
namespace LettersLibrary {
export class A {
hello = "Hello World";
}
export class B {
myBool = false;
}
export class C {
someInt = 42;
}
}
In JavaScript, you would then do:
const instance = new LettersLibrary.A ();
console.log (instance.hello); // "Hello World"
If you need to re-export classes from other files, just export the imported class as const and type (useful for TypeScript development, otherwise you will not be able to use the type from the module):
import importA from "...";
import importB from "...";
import importC from "...";
namespace LettersLibrary {
export const A = importA;
export type A = importA;
// Same for B and C
}
When using WebPack, you will have to export it as a library. For this, you can use the libraryExport
configuration together with the library
and libraryTarget
options. See: https://webpack.js.org/configuration/output/#output-libraryexport
Thanks to @Ghabriel Nunes, who informed me that module
s are now named namespace
s.
es6
brings modules natively. Just be es compliant. – Hitmands Commented Dec 14, 2017 at 14:47