简体   繁体   中英

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

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.

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 eg 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM