How to use npm link with a module written using TypeScript for development?

Denys Kozak picture Denys Kozak · Oct 19, 2019 · Viewed 7.6k times · Source

I am building a lib using TypeScript and Webpack.

To develop this library I have created a separate test project (written using JS) and linked the library using npm link <package-name>.

The problem is that the link leads to the build file and I need to run npm run build every time I make a change.

I want to have a link to the source file and have a live reload. Is it possible? Do I need to write my test project using TS also to make it possible?

Library package.json:

{
  ...
  "main": "lib/qr-code-styling.js",
  "files": [
    "lib"
  ],
  "scripts": {
    "build": "webpack --mode=production"
  },
  ...
}

Code of the library https://github.com/kozakdenys/qr-code-styling/tree/v1

Code of test project https://github.com/kozakdenys/qr-code-styling-site

P.S. I also tried "module": "src/index.ts" in package.json, but it causes an error in the test project Uncaught Error: Cannot find module './core/QRCodeStyling'

Answer

mekwall picture mekwall · Oct 19, 2019

Yes, you need to write your test project in TypeScript as well. After that you need to map the package to the linked module source files in the test project tsconfig file.

In the compilerOptions entry of the tsconfig file add a baseUrl and a paths entry like the following the example:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "linked-module-name": ["node_modules/linked-module-name/src"],
      "linked-module-name/*": ["node_modules/linked-module-name/src/*"]
    }
  }
}

Read more about path mapping in the TypeScript docs.