Typescript: Question: type definitions for dual packages

Created on 28 Oct 2020  路  7Comments  路  Source: microsoft/TypeScript

Search Terms

esm, commonjs, dual packages

Question

foo/package.json
    foo/index.mjs   (this is ESM)
    foo/index.cjs  (this is CJS)
    foo/index.d.ts (this is type definitions)

for example, index.mjs and index.cjs has function declare function arch(): 'x64' | 'x86';

For cjs, index.d.ts should be

declare function arch(): 'x64' | 'x86';
export = arch;

For mjs, index.d.ts should be

declare function arch(): 'x64' | 'x86';
export default arch;

For both, index.d.ts should be

declare function arch(): 'x64' | 'x86';


declare const Arch: typeof arch & {
  readonly default: typeof arch;
}
export = Arch;

But If I use export = Arch;

import arch = require('arch');

arch.default() // This has no error. But `arch.default` is not exists.
Needs Investigation

All 7 comments

No, I don't want to open allowSyntheticDefaultImports, bacause import arch from 'foo' will import foo/index.mjs. It should works well.

@Kingwl is right - you should define the package types as

declare function arch(): 'x64' | 'x86';
export = arch;

(so the cjs one) in index.d.ts, and compile with esModuleInterop or allowSyntheticDefaultImports on - either flag will allow you to import a package defined like the above as a default import - import arch from 'foo'. (The first of the two will also generate some helpers in cjs emit to preserve that behavior at runtime between transpiled packages)

@weswigham What should I do if I want to provide dts for users who disable allowSyntheticDefaultImports and esModuleInterop.

@xiaoxiangmoe
That聽will most聽likely depend聽on support聽for the聽exports聽field in聽TypeScript.

Yes.
@weswigham Will TS support the exports field?

@xiaoxiangmoe
That鈥檚聽being聽tracked in聽issue聽https://github.com/microsoft/TypeScript/issues/33079.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

wmaurer picture wmaurer  路  3Comments

bgrieder picture bgrieder  路  3Comments

jbondc picture jbondc  路  3Comments

DanielRosenwasser picture DanielRosenwasser  路  3Comments

CyrusNajmabadi picture CyrusNajmabadi  路  3Comments