I have a library that is written in TypeScript and uses internally absolute imports to avoid deeply nested relative import statements, like
import {Something} from '../../../../root-level-module';
and instead write
import {Something} from 'root-level-module';
To get it to compile correctly, I use
{
"compilerOptions": {
"baseUrl": "./src"
}
}
in my tsconfig.json.
I am able to transform these import statements correctly in the emitted ES modules, using babel-plugin-module-resolver.
The npm package also includes the .d.ts type declaration files (1 per .js file) which are emitted using tsc --emitDeclarationOnly.
The problem is that the import statements in the declaration files are not transformed, so they cannot be read by the consumer of this package.
As far as I can see, TypeScript itself does not provide any way to emit the results of its internal path resolution mechanism: https://www.typescriptlang.org/docs/handbook/module-resolution.html
I tried some type declaration bundlers and some typescript transformers but couldn't get it to work correctly.
This is related to another particular issue with my library: it uses babel-plugin-inline-react-svg to transform SVG files that are imported into React components. This is supported by a type declaration (svg.d.ts):
declare module '*.svg' {
...
}
The compiler understands import statements such as import Icon from 'icon.svg'; correctly and they are correctly transformed by babel in the emitted .js files, but I am unable to get the type declaration files to be correct in a way that the library can be used by any other project.
So, am I missing something here? What would be the correct approach for writing a TypeScript library (as an NPM package) that:
- is compiled into ES modules and not bundled
- has type declarations (either bundled or not)
- can use absolute imports internally (to avoid deeply nested relative imports)
- can use the babel plugin to convert SVG files into React components ?