I'm currently working on a private npm package in TypeScript that needs to be reused in multiple TS projects. To streamline this process, I created and published the @myorg/core
package, containing enums and types that are shared across different repositories.
In the tsconfig.json
file of the package, I have set "declaration": true
to export API descriptions into .d.ts files upon building.
The project structure involves:
src/
├── enumerators/
│ └── index.ts
├── database-models/
│ └── index.ts
├── external-apis/
│ └── index.ts
└── index.ts
The purpose of src/index.ts
is to export all resources with the following code:
export * as ExternalAPIs from './external-apis';
export * as Enumerators from './enumerators';
export * as DatabaseModel from './database-model';
My goal now is to figure out how to directly import these resources. Instead of using:
import * as MyOrgCore from '@myorg/core'
I would prefer to use:
import * as Enumerators from '@myorg/core/Enumerators'
After researching online, I found suggestions regarding the exports field in the package.json file, simplified as shown below:
{
"name": "@myorg/core",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"exports": {
".": "./dist/index.js",
"./Enumerators": "./dist/enumerators/index.js",
"./ExternalAPIs": "./dist/external-apis/index.js",
"./DatabaseModels": "./dist/database-model/index.js"
}
}
Despite implementing this, I still encounter the error message:
Cannot find module '@myorg/core/Enumerators' or its corresponding type declarations.ts(2307)
So my final question remains: what is the correct approach for achieving this? And is it considered a good practice?