Different ways to run a locally installed node-package

Different ways to run a locally installed node-package

We all know that you can install a node-package globally or locally (package.json).

But what happens if I install for example the typescript-compiler locally and start the compiler directly in the terminal?

Let's do it...

Install typscript-compiler locally

npm install --save-dev typescript

Try to get the version of the typescript-compiler

tsc --version

Ups! I guess you expected to see the version of the compiler right?
But instead you see an output like: tsc command not found

Because if you call the typescript-compiler cli directly via tsc the terminal is looking for an globally installed typescript-compiler node-package.

But sometimes you don't wanna install typescript globally or you need to run the specific version of the locally installed typescript-compiler.

But how can I start a npm-package locally?

I would like to show you 3 different ways to do it:

1. Run tsc using npx

When TypeScript is installed locally, you can use npx to execute the local tsc without needing a global installation. Run the following command in your terminal:

npx tsc --version

2. Run tsc directly from node_modules/.bin

Alternatively, you can run the tsc command directly from the local node_modules/.bin directory where local executables are stored:

./node_modules/.bin/tsc --version

3. Add a script in package.json

For convenience, you can add a custom script to your package.json to run the TypeScript compiler. Add the following in the "scripts" section of your package.json:

{
  "scripts": {
    "tsc:version": "tsc --version"
  }
}

Then, you can run the TypeScript compiler by simply running:

npm run tsc:version

Summary

  • Use npx tsc for a one-off execution.

  • Add a build script in package.json for easier execution with npm run build.

  • Directly execute ./node_modules/.bin/tsc if preferred.