【问题标题】:How to add TypeScript definition files to source control?如何将 TypeScript 定义文件添加到源代码管理?
【发布时间】:2019-04-30 13:07:02
【问题描述】:

我有一个简单的 asp.net 核心 Web 应用程序,我在其中使用 libman 安装了 javascript 库。

我想使用 typescript,所以我已经为使用 npm 的库安装了 typescript 定义文件,例如:

npm install @types/jquery --save-dev
npm install @types/bootstrap --save-dev

我想将 .d.ts 文件添加到源代码管理中,这样其他开发人员就不必依赖 NPM - 这是 libman 的目的,不是吗?

/node_modules 文件夹在 .gitignore 中默认被忽略。

如何包含打字稿定义文件?

【问题讨论】:

  • .gitignore中删除node_modules
  • 问题是 node_modules 包含很多垃圾、自述文件、json 文件、javascript 文件……为什么这个问题被否决了?

标签: git typescript asp.net-core npm libman


【解决方案1】:

由于您已经使用 LibMan 安装了 javascript 库,因此您也可以简单地重复使用 LibMan 来安装定义:

libman install @types/jquery -p unpkg
libman install @types/bootstrap -p unpkg

默认路径为libs/@types

lib/
    @types/
        bootstrap/
            index.d.ts
            ...
        jquery/
            index.d.ts
            ...

我创建一个tsconfig.json 并配置路径映射以加载模块,如下所示:

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "jquery": ["lib/@types/jquery"] ,
            "bootstrap":["lib/@types/bootstrap"]
        }
      }
}

现在我们可以从打字稿中受益:

[更新]

对于 ASPNET-CORE 项目,默认路径为:wwwroot/lib/@types,如果我们在项目目录下(在*.csproj 项目文件旁边)有我们的tsconfig.json,我们需要将路径更改为:

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "jquery": ["wwwroot/lib/@types/jquery"] ,
            "bootstrap":["wwwroot/lib/@types/bootstrap"]
        }
      }
}

【讨论】:

  • 很好,但是我无法使用全局变量,输入 $ 或 jQuery...
  • @Liero 你是通过import $ from "jquery" 导入jquery 吗? “jquery”模块不会导出$,因此我们需要将所有内容导入为$jQuery
  • 不,但使用 npm install @types/jQuery 我不必这样做。由于 cdn 包使用全局变量 $,类型定义也应该..
  • 我在@types/jquery/misc.d.ts 中看到了declare const $: JQueryStatic。我想问题出在 tsconfig.json 上,它的默认值可能与 csproj 中的 <TypeScriptCompile> 不同……。
  • @Liero 您能否详细说明“但我不必使用 npm install @types/jQuery”。我刚试了npm i @types/jQuery ,下载的文件一模一样。你配置好路径映射了吗?
【解决方案2】:

对于那些宁愿自己输入的人:libman install @types/jquery -p unpkg 生成的 JSON

{
    "provider": "unpkg",
    "library": "@types/jquery@3.3.29",
    "destination": "wwwroot/js/lib/@types/jquery"
}

(注意:我有一个现有的libman.json 文件,它已添加到"libraries" 数组中)

【讨论】:

    猜你喜欢
    • 2011-08-14
    • 1970-01-01
    • 2010-12-19
    • 1970-01-01
    • 2011-06-07
    • 2017-12-07
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多