Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Webpack alias with TypeScript Declaration

I am writing a NPM package with TypeScript but I could not find a way to convert Webpack alias in TypeScript Declaration.

webpack.config.js

{
  // ...more Webpack configurations
  resolve: {
  extensions: [".ts", ".js"],
  alias: {
    "@": resolvePath("src")
  }
}

tsconfig.json

{
  "compilerOptions": {
    // More options
    "paths": {
      "@/*": ["src/*"]
    }
  }
}

I am using babel-loader with @babel/preset-typescript but it does not output declaration files.

tsc --emitDeclarationOnly emits declaration files but it does not replace @/ with correct path. Same for ts-loader.

I am able to get it working in Jest with moduleNameMapper. If I can get it working building declaration files, I not longer need to write somethings like ../../../../model.

Most of the answers I found online is about compiling JavaScript files, which I don't have a problem with. Any help will be appreciated.

like image 278
Joshua Avatar asked Apr 16 '19 04:04

Joshua


People also ask

Do I need to use webpack with TypeScript?

For Webpack, we need webpack and webpack-cli package and for TypeScript features, we need typescript and ts-loader packages. Now that all the dependencies are ready to be used, we need to create the webpack.

What does webpack alias do?

Aliases are a way to let webpack know where to find our code by providing a word or character that represents a partial reference to where the code is located. Once webpack knows this, the code can be properly resolved while it is compiling during development or building the final package.


1 Answers

I finally find a solution. You need ttypescript and typescript-transform-paths. You add the following to compilerOptions in tsconfig.json

"plugins": [
  { "transform": "typescript-transform-paths", "afterDeclarations": true }
]

and run

ttsc --emitDeclarationOnly

I wrote an article on this.

like image 132
Joshua Avatar answered Oct 16 '22 10:10

Joshua