How to have npm install a typescript dependency from a GitHub url?

I had the same problem. Saw a lot of articles about monorepos (links below), but not much about how to split a TypeScript project into separate repositories.

In short, you need to build JS files at one step or the other.

See https://github.com/stared/yarn-adding-pure-typescript-package-example for a working code example.

So, there are a few solutions. Let’s say that the repository is someuser/package-to-import

Postinstall

Using yarn you can get the project directly from a GitHub repository:

yarn add someuser/package-to-import#master

(or the same with npm install someuser/package-to-import#master)

If you work on a fork of this repository, you can make your life easier by adding to package.json in package-to-import repo this part:

  "scripts": {
    ...,
    "postinstall": "tsc --outDir ./build"
  }

Now it just works with yarn add/upgrade with no extra scripts.
Alternatively, you can do it semi-manually, i.e. create a script in your main repository package.json

  "scripts": {
    ...,
    "upgrade-package-to-import": "yarn upgrade package-to-import && cd node_modules/package-to-import && yarn build"
  }

Link

There is a different approach to clone the repository into a different folder, build the files, and link it.

git clone git@github.com:someuser/package-to-import.git
cd package-to-import
npm run build  # or any other instruction to build
npm link

If you use yarn, the two last lines would be:

yarn build
yarn link

Then, enter the folder of your project and write

npm link package-to-import

or in case of yarn

yarn link package-to-import

These are symlinks, so when you pull from the repo and build files, you will use the updated version.

See also:

  • npm link andyarn link official documentations
  • The magic behind npm link

Monorepos

An entirely different approach.
With mixed advice for using git submodules:

  • 4 Ways to Go Monorepo in 2019
  • 4 Git Submodules Alternatives You Should Know
  • A (multi-) monorepo setup with Git Submodules

Leave a Comment