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.
You can create type definition files for any proprietary JavaScript code. Even if a JavaScript library doesn't have a type definition file, you can still use it in your TypeScript project.
A module can be created using the keyword export and a module can be used in another module using the keyword import . In TypeScript, files containing a top-level export or import are considered modules. For example, we can make the above files as modules as below. console.
The TypeScript compiler supports a mix of JavaScript and TypeScript files if we use the compiler option --allowJs : TypeScript files are compiled. JavaScript files are simply copied over to the output directory (after a few simple type checks).
The allowJs setting allows JavaScript files to be imported inside your TypeScript files. The setting basically allows JavaScript and TypeScript files to live in the same project.
Use 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With