If you are only interested in the final outcome you inquired about and do not necessarily need to utilize TypeScript's module
syntax, you can simplify the process and explore a few options.
To simplify, you can remove the
export module mylib { /* ... */ }
wrappers in
Foo.ts
and
Bar.ts
, and simply have:
export class Foo
// ...
}
and
export class Bar
// ...
}
After this, it's a matter of how you want these classes to be imported from index.ts
.
Module namespace object
The current setup in index.ts
works well for creating two named exports, Foo
and Bar
. If you wish to access these via a mylib
object, you can achieve that during import:
import * as mylib from "../src";
// ^^^^^^^^^^
By using this import
syntax, you are essentially saying "Import the module namespace object for the module and assign it to a binding called mylib
." If the module namespace object does not exist, it will be created.
Once imported, you can use it as demonstrated in the question, for example, mylib.Foo
.
However, with this approach, you could also use import { Foo }
and/or import { Bar }
. This flexibility may or may not be desirable based on your requirements.
Keep in mind that using import * as mylib
could impact tree-shaking, which may be a consideration for your project. Ultimately, it is up to the consumer of your library to decide on this aspect.
Export an object
If you prefer not to go with the module namespace object approach, you could export an object directly from index.ts
:
export const mylib = { Foo, Bar };
...or you could export a frozen object to prevent modifications to its properties:
export const mylib = Object.freeze({ Foo, Bar });
In this case, the import statement would be as shown in the question:
import { mylib } from "../src";
And you would access the classes using mylib.Foo
and similar.
Keep in mind that this approach also hinders tree-shaking, not just based on how it's used, but at the library level as well. It might not be the most recommended option.
Both
Lastly, you could support both individual named exports and a single named object export. In this scenario, the exports in index.ts
would look like this:
export { Foo, Bar };
export const mylib = Object.freeze({Foo, Bar});
This way, users have the choice to import Foo
individually or the entire mylib
object. This maintains tree-shaking efficiency while offering a convenient named export for the library.