I need some guidance to correctly develop reusable commonjs library (npm package). Lets say the library structure is the following:
—lib
——Helper.ts
——Serialization.ts
——meta
——— Entity.ts
—index.ts
And so on. Each file is external module.
Now I need to create entry file (say index.ts) that will expose functionality of the library and will serve as entry point. Here I can’t wrap my head around the way to create it. I would like to keep the nested structure without flattening it by exporting everything:
export * from './lib/Helper’;
export * from './lib/Serialization’;
export * from './lib/meta/Entity’;
…
Cause this will remove logical grouping and can in the future lead to possible name conflicts
I have also tried to have index.ts like this:
import {Helper} from './lib/Helper';
import * as Serialization from './lib/Serialization';
import * as Decorators from './lib/meta/Decorators';
let core = {
Helper: Helper,
Serialization: Serialization,
Meta: {
Entity: Entity,
}
}
export default core;
It works perfect until I come to consume imported types like this:
import Core from ’nameOfTheNpmPackage';
let Entity = Core.Meta.Entity;
function f(e: Entity)//<—This produce error cannot find name ‘Entity'
{
}
As they are not in the type declaration space (is there a way of copying them there if they are not in namespace?)
Another option I have tried is generating single d.ts file for the whole library by using outFile + amd. But that file is not an external module.
So my question is - how is it possible to write index.ts so that it will be external module and export all functionality exposed by library.
Thanks in advance.
One day of wasted time and I've come up with ugly solution.
To keep nested structure of the exported commonjs library you must inside each 'level' put its own index.ts
that will aggregate and reexport all functionality of the same 'level'. For my sample above it will look like:
—lib
——Helper.ts
——Serialization.ts
——meta
——— index.ts
——— Entity.ts
—index.ts
Where root index.ts:
export * from './lib/Helper';
export * from './lib/Serialization';
import * as S from './lib/Serialization'; //This is case where one file contains several exported classes that we want to keen as separate module
export {S as Serialization};
import * as Meta from './lib/meta/index';
export {Meta};
And meta/index.ts:
export * from './Entity';
I would be really glad to know if this common(?) task is possible to solve without extra files per 'level'.