What's the most efficient way to emit type declarations?
Asked Answered
P

1

9

What's the most efficient way to emit type declarations for a Typescript project (library) along with code transpiling and bundling?

I'm using webpack, ts-loader and fork-ts-checker-webpack-plugin.

In one build cycle (build command) I'm trying to get:

  1. dev version of the library (unminified, inline source maps, etc)
  2. prod version of the library (minified + separate source map file)
  3. type declaration

The first 2 options are working well with fork-ts-checker-webpack-plugin. With thread-loader and cache-loader thrown into the mix things get even better. However, the way they work doesn't allow for emitting of .d.ts files.

So what I'm trying to figure out what is the best way to emit such files.

Right now the options that I see:

  1. Use tsc at the end of code bundling. Run it with spawnSync, for example.
  2. Create another webpack config object to run webpack exclusively in the emitDeclarationOnly mode
  3. Run ts-loader with {transpileOnly: false, happyPackMode: false}, but that defeats the goal of using threads

What might be faster in general? Is there another approach?


My own answer for the time being that seems to work:

In webpack.config.js somewhere above the part that exports your webpack config, add the following (tweak arguments to suit your needs):

spawn("tsc", ["-p", "src", "--emitDeclarationOnly", "--declaration", "--declarationDir", "dist/@types", "--skipLibCheck"]);

This code will spawn a child process and run in parallel with whatever webpack is going to do. So now webpack doesn't have to worry about Typescript types at all.

Pierrette answered 5/9, 2018 at 15:45 Comment(0)
R
0

If you aim to run webpack by npm or yarn then first two steps means - dev and prod builds would be handled by webpack multiconfig. The types generation step then by npm/yarn custom post command called e.g. postbuild if build script provided

"scripts": {
    "postbuild": "tsc -p tsconfig.json --emitDeclarationOnly --declaration --declarationDir ./dist/@types --skipLibCheck",
    "build": "webpack"
}

All there steps takes place by executing single command

yarn build

or

npm run build

Refugio answered 3/9, 2020 at 10:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.