I have a unique package structure that includes:
myPackage/
|- types/
| |- type1.d.ts
| |- type2.d.ts
|- src/
| |- someUtilities.ts
|- index.ts
|- package.json
|- tsconfig.json
In my package, the index.ts
file is handling imports and exports for all the .d.ts
files in the types
directory and all the .ts
files in the src
directory. After transpiling with tsc
, I end up with this new structure:
myPackage/
|- types/
| |- type1.d.ts
| |- type2.d.ts
|- src/
| |- someUtilities.ts
|- index.d.ts
|- index.js
|- package.json
The index.d.ts
file contains all the necessary type imports and exports, while index.js
holds the transpiled code from the src
directory. Thus far, everything is working correctly.
Now, when I try to use this internal package in another project (CRA), I run into an issue during the build process. Although Visual Studio Code recognizes all the types and functions from the package during development, running npm run build
results in the error message:
Module not found: Can't resolve './types/type1.d.ts' in '/node_modules/myPackage'
.
To address this problem, I attempted creating an index file under the types directory and specifying it in the package's package.json
. While this solution helped with finding types during the build, it couldn't locate the transpiled types from the source files.
myPackage/
|- types/
| |- type1.d.ts
| |- type2.d.ts
| |- index.d.ts <- successfully handles imports when used as a dependency in other projects
|- src/
| |- someUtilities.ts
|- index.d.ts <- remains undiscovered because package.json points to types/index.d.ts
|- index.js
|- package.json
I then experimented with consolidating all the types into one index file at the root of the package and relying on triple-slash directives to reference them. While somewhat effective, this approach required full path specifications when importing types in other projects.
// index.ts at package root
/// <reference path="./types/type1.d.ts">
/// <reference path="./types/type1.d.ts">
import { someUtility } from './src/someUtilities'
export { someUtility }
// Doesn't work
import { someType } from 'myPackage'
// Works
import { someType } from 'myPackage/path/to/the/type/file'
Is there a way to separate and bundle all the types into individual files so they can be imported from the index, or must I manually combine them into a single, large index.d.ts
file for usage? Managing a massive declaration file like that would be cumbersome, especially considering each declaration file has its own namespace within the types directory.