Configure local typescript compiler inside package.json

Yves Schelpe picture Yves Schelpe · Feb 16, 2017 · Viewed 9.1k times · Source

EDIT #1: seems like I have a working configuration, all suggestions to improve this are welcome though. See answer: https://stackoverflow.com/a/42269408/1155847


ORIGINAL QUESTION:

I'm currently trying to setup my environment so that my package.json's devDependencies typescript version will be used. What are some of the best practices for this, so that it is "editor unaware" and preferably can be used as an npm script, e.g.: npm run tscompile?

To be clear - I can get everything working when using npm install typescript -g - but then I'm relying on a global installed version, whic is not what I want - as we'll want to work in a team and set on a specific typescript version for each member before upgrading, so we're all on the same page.

I'm currently trying to set it up like this - yet npm then complains it doesn't recognize "node_modules" as an internal or external command... I presume I do have to pass the tsconfig.json to tsc as well, or at least give it the "working directory" - but I can't even get past launching tsc from my locally downloaded npm cache.

package.json

{
  "name": "tswithnodejsgettingstarted",
  "version": "1.0.0",
  "description": "",
  "main": "app/index.js",
  "scripts": {
    "start": "node app/index.js",
    "tscompile": "node_modules/typescript/tsc"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "typescript": "2.1.6"
  }
}

tsconfig.json

{
    "compileOnSave": true,
    "compilerOptions": {
        "module": "commonjs",
        "noImplicitAny": true,
        "sourceMap": true,
        "outDir": "app"
    },
    "include": [
        "src/**/*.ts"
    ],
    "exclude": [
        "node_modules"
    ]
}

Answer

Yves Schelpe picture Yves Schelpe · Feb 16, 2017

Ok... It seems like it was as simple as this (see below). Answering it here, for anyone else looking for the answer. Or please let me know if there are better solutions.

Configure the script like "tsc": "tsc" inside package.json. Then just run npm run tsc and it will use your tsc version you have installed locally, and discover your tsconfig.json of course. It doesn't use your global version - as I uninstalled that one - just entering tsc in the command line errors out.

E.g.:

Check the repo* where I was playing with this.

package.json

{
  "name": "tscnodejsgettingstarted",
  "version": "1.0.0",
  "description": "",
  "main": "app/index.js",
  "scripts": {
    "start": "npm run tsc && node app/index.js",
    "tsc": "tsc"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "typescript": "2.1.6"
  }
}

*repo: https://github.com/pluralsight-courses/typescript-fundamentals/tree/master/001-GettingStarted