Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion - Improve type definitions generation example to support extended tsconfig files. #45

Open
gablabelle opened this issue Jul 4, 2021 · 0 comments

Comments

@gablabelle
Copy link

gablabelle commented Jul 4, 2021

A lot of monorepo projects will make use of the extends property in their tsconfig files in order to keep things DRY where possible. It took me a few minutes to understand what was wrong with my config.

Quick example:

{
  "extends": "../../tsconfig.settings.json",
  "compilerOptions": {
    "composite": true,
    "outDir": "dist",
    "rootDir": "src"
  },
  "include": ["src/**/*"]
}

...tsconfig.compilerOptions,

Here are the changes I've had to make to the generateTypeDefs function in the example.

function generateTypeDefs(config, entryfiles, outdir = 'dist') {
  const filenames = Array.from(
    new Set(
      (Array.isArray(entryfiles) ? entryfiles : [entryfiles]).concat(
        config.include || [],
      ),
    ),
  ).filter((v) => v);
  log.info('Generating type declaration files for', filenames.join(', '));
  let extendedCompilerOptions = {};
  if (config.extends) {
    const rawExtendedTsConfig = fs.readFileSync(config.extends);
    const extendedTsConfig = JSON.parse(rawExtendedTsConfig);
    if (extendedTsConfig.compilerOptions) {
      extendedCompilerOptions = extendedTsConfig.compilerOptions;
    }
  }
  const compilerOptions = {
    ...extendedCompilerOptions,
    ...config.compilerOptions,
    moduleResolution: undefined,
    declaration: true,
    outDir: outdir,
  };
  const program = ts.ts.createProgram(filenames, compilerOptions);
  const targetSourceFile = undefined;
  const writeFile = undefined;
  const cancellationToken = undefined;
  const emitOnlyDtsFiles = true;
  program.emit(
    targetSourceFile,
    writeFile,
    cancellationToken,
    emitOnlyDtsFiles,
  );
  log.info('Wrote', glob(`${outdir}/*.d.ts`).join(', '));
}

Hope it helps.

@gablabelle gablabelle changed the title Suggestion - Improve type definition generation example to support extended tsconfig files. Suggestion - Improve type definitions generation example to support extended tsconfig files. Jul 4, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant