在 package.json 中配置本地打字稿编译器

Yve*_*lpe 10 node.js npm typescript tsconfig visual-studio-code

编辑 #1:似乎我有一个有效的配置,但欢迎提出所有改进建议。见答案:https : //stackoverflow.com/a/42269408/1155847


原问题

我目前正在尝试设置我的环境,以便使用我package.jsondevDependencies打字稿版本。什么是一些我们的最佳实践,所以它是“编辑不知道”,最好可以用作NPM脚本,如:npm run tscompile

需要明确的是 - 我可以在使用时让一切正常npm install typescript -g- 但是我依赖于全局安装版本,这不是我想要的 - 因为我们希望在一个团队中工作并为每个版本设置特定的打字稿版本升级之前的会员,所以我们都在同一页面上。

我目前正在尝试像这样设置它 - 但是npm然后抱怨它无法将“node_modules”识别为内部或外部命令......我想我也必须将 tsconfig.json 传递给 tsc,或者在至少给它一个“工作目录”——但我什至无法从我本地下载的 npm 缓存中启动 tsc。

包.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"
  }
}
Run Code Online (Sandbox Code Playgroud)

配置文件

{
    "compileOnSave": true,
    "compilerOptions": {
        "module": "commonjs",
        "noImplicitAny": true,
        "sourceMap": true,
        "outDir": "app"
    },
    "include": [
        "src/**/*.ts"
    ],
    "exclude": [
        "node_modules"
    ]
}
Run Code Online (Sandbox Code Playgroud)

Yve*_*lpe 7

好吧……看起来就这么简单(见下文)。在这里回答,供其他人寻找答案。或者请让我知道是否有更好的解决方案

"tsc": "tsc"inside一样配置脚本package.json。然后运行npm run tsc,它会使用你在本地安装的 tsc 版本,当然会发现你的 tsconfig.json。它不使用您的全局版本 - 因为我卸载了那个 - 只是tsc在命令行中输入错误。

例如:

检查repo * 我在那里玩这个。

包.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"
  }
}
Run Code Online (Sandbox Code Playgroud)

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


Thi*_*nho 6

您也可以使用该prestart脚本。默认情况下,它在启动命令之前运行(请参阅您可以在此处设置的所有默认脚本)。

  "scripts": {
    "prestart": "npm run tsc",
    "start": "node app/index.js",
    "tsc": "tsc"
  }
Run Code Online (Sandbox Code Playgroud)