egoist / tsup

The simplest and fastest way to bundle your TypeScript libraries.
https://tsup.egoist.dev
MIT License
9.01k stars 217 forks source link

values wrongly initialize in dts when importing json #1012

Open SuperchupuDev opened 1 year ago

SuperchupuDev commented 1 year ago

having the following config:

import { defineConfig } from 'tsup';

export default defineConfig({
  clean: true,
  dts: true,
  entry: ['src/index.ts'],
  format: ['esm', 'cjs'],
  platform: 'node',
  sourcemap: true,
  target: 'es2022'
});

and this (example) typescript code:

export { default as whatever } from './whatever.json';

export function something(): boolean {
  return true;
}

tsup adds the following to the declaration files when exporting a json file in one of the ts files:

var whatever = [
    "whatever json values the file has"
];

// other dts values (which are correct)
declare function something(): boolean;

export { something, whatever }

this makes typescript throw Initializers are not allowed in ambient contexts. ts(1039)

the solution would be to actually resolve the json type (just like how plain typescript does under resolveJsonModule) and type it as such

for example:

declare const whatever: string[];

declare function something(): boolean;

export { something, whatever }

another solution would be to just use valid dts syntax, this would be easier to implement as tsup wouldn't have to resolve the json type, but it would increase filesize

declare const whatever: [
    "whatever json values the file has"
];

declare function something(): boolean;

export { something, whatever }

Upvote & Fund

Fund with Polar

codetheweb commented 6 months ago

for anyone else running into this, I was able to work around it by casting the import as any

e.g. in the example above:

import { default as whateverTyped } from './whatever.json';

export const whatever = whateverTyped as any

export function something(): boolean {
  return true;
}