【发布时间】:2019-05-01 08:58:29
【问题描述】:
当我使用 npm 安装 typescript 定义时,我可以在属于 Visual Studio 构建的 typescript 文件中使用它们:
- 在 Visual Studio 中创建新的 ASP.NET Core Web 应用程序
- 使用 libman 添加 jQuery
- 使用
npm install @types/jQuery添加jQuery - 创建新的打字稿文件:wwwroot/js/site.ts。这会将
<TypeScriptCompile Include="wwwroot\js\site.ts" />添加到 .csproj。 - 我现在可以在我的打字稿文件中使用
$全局变量
但是,当我使用 libman 下载 typescript 定义时,我在配置 typescript 构建以使用它们时遇到了麻烦。
我想我需要添加tsconfig.json,但它似乎干扰了csproj中的TypeScriptCompile。
wwwroot
js
site.d.ts
site.ts
lib
jquery
jquery.min.js
@types
jquery
index.d.ts
misc.d.ts
…
MyProject.csproj
libman.json
如何修改项目(.csproj、tsconfig.json),以便使用 wwwroot\lib\@types 中的定义文件和全局变量而不是 node_modules/@types?
我已经创建了 tsconfig.json 并设置了
"compilerOptions": {
"typeRoots": [ "wwwroot/lib/@types" ]
}
但现在构建在 site.ts 中返回诸如“找不到名称 MyInterface”之类的错误。 MyInterface 在 site.d.ts 中定义。为什么在没有 tsconfig.json 时可以识别类型,而现在却没有?我想避免添加///<reference> cmets
编辑:
我最终将 site.d.ts 重命名为 global.d.ts(感谢 @itminus answer),并在 tsconfig 中明确设置 popper.js 模块的路径:
{
"compileOnSave": true,
"compilerOptions": {
"baseUrl": "./",
"paths": {
"popper.js": [ "wwwroot/lib/popper.js" ] //use this instead of wwwroot/lib/@types/popper.js which is incompatible
},
"typeRoots": [ "wwwroot/lib/@types" ]
},
"include": [ "wwwroot/js/**/*.ts" ]
}
popper.js 是 bootstrap 4 的依赖项。这有点棘手,因为 @types/bootstrap 依赖于 popper.js 而不是 @types/popper.js(这是不兼容的,并且会在 @types/bootstrap/index.d 中引发 typescript 错误.ts);
幸运的是,popper.js 包含 typescript 定义 (index.d.ts),我只需要告诉 typescript 编译器在哪里查看它。
【问题讨论】:
-
在第三步中是不是 libman install 而不是 npm?
-
@g.pickardou 你也可以在 VS 中使用 libman 的 GUI 来安装类型。只需选择 unpkg 并输入 @types/jquery@3.3.1
标签: visual-studio typescript asp.net-core libman