Seeking advice on generating TypeScript ambient module declarations for a node (commonjs) npm package being developed in TypeScript. Encountering confusion around the proper method to have TypeScript create these ambient module declarations for node / commonjs.
Our npm package is published as a scoped module, such as "@company/module". To ensure TypeScript can resolve the "scoped" module, it requires a fully qualified ambient module name declaration like "@company/module". However, we are unsure about the generation of named ambient modules and the correct way to generate ambient module declarations from the compiler.
Our module structure resembles the example below.
TypeScript
The code is compiled into index.js and bar.js respectively.
// ./bar.ts
export class Bar {}
// ./index.ts
import { Bar } from "./bar"
export class Foo {
constructor(private bar: Bar) {}
}
TypeScript Declaration
We aim to generate the following idealized output from the typescript compiler.
// ./index.d.ts
declare module "@company/module/bar" {
export class Bar {}
}
declare module "@company/foo" {
import { Bar } from "@company/module/bar"
export class Foo {
constructor(private bar: Bar)
}
}
There doesn't seem to be a straightforward way to directly generate the above declaration from TypeScript. Our workaround involves:
- Compiling the declaration separately using module: AMD - outFile (emits declaration bundle and "ambient" declarations).
- Rewriting the compiled AMD declaration and prefixing declare module with "@company/module" (including the import).
There are ongoing github issues in the TS repository regarding generating bundled declarations in this manner, which are linked below.
Package declaration file for commonjs packages - (seems perfect) https://github.com/Microsoft/TypeScript/pull/3159
Proposal: Bundling TS module type definitions https://github.com/Microsoft/TypeScript/issues/4434
Interested in hearing others' experiences with publishing npm declaration files for TypeScript libraries on NPM. Open to all suggestions!
Thank you.