有没有办法在 TypeScript 2+ 中全局添加类型定义? [英] Is there a way to add type definition globally in TypeScript 2+?

查看:47
本文介绍了有没有办法在 TypeScript 2+ 中全局添加类型定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆简单的 .ts 文件.非项目(即独立的 .ts 脚本).他们使用一些 node.js 功能.TypeScript 和节点类型定义通过

I have a bunch of simple .ts files. NOT projects (i.e. standalone .ts scripts). They use some node.js functionality. TypeScript and node type definitions are installed via

npm install -g typescript
npm install -g @types/node

问题:在 Windows 上我可以毫无问题地运行 tsc foo.ts.它可以很好地将 .ts 转换为 .js.但是在 Ubuntu 16.04 上,它给了我 error TS2304: Cannot find name 'require'error TS2304: Cannot find name 'process' 等.即使将 /// 添加到 foo.ts 的顶部或添加 --types node> 切换到 tsc 我收到 错误 TS2688:找不到节点"的类型定义文件.

Problem: on windows I can run tsc foo.ts with no problems. It transpiles .ts to .js just fine. But on Ubuntu 16.04 it gives me error TS2304: Cannot find name 'require', error TS2304: Cannot find name 'process' and etc. Even if add /// <reference types="node" /> to the top of foo.ts or add --types node switch to tsc I get error TS2688: Cannot find type definition file for 'node'.

看起来在 Windows 中全局安装某些类型可以正常工作,但在 Ubuntu 上则不行,所以我假设这不是设计使然.那么有没有办法全局安装它们?或者更准确地说:在 Ubuntu 上引用全局安装的类型定义?

It looks like installing some types globally works fine in Windows but not on Ubuntu, so I'm assuming that this is not by design. So is there a way to install them globally? Or more precisely: to reference globally installed type definitions on Ubuntu?

推荐答案

我找到了解决方案.我必须手动指定 typeRoots 和通向 npm 安装的全局包的路径.像这样:tsc --typeRoots/usr/lib/node_modules/@types(您可以通过 npm root -g 获取系统路径).

I found the solution. I had to manually specify the typeRoots with the path leading to there npm installed global packages. Like so: tsc --typeRoots /usr/lib/node_modules/@types (you can get the path for your system via npm root -g).

仍然不知道为什么它在 Windows 上没有任何特殊工作的情况下查找它们,而在 Ubuntu 上没有.不知道是不是bug,不知道是哪个版本.

Still not sure why it looks them up without any special work on Windows and doesn't on Ubuntu. Can't tell if it's a bug and if it is then in which version.

这篇关于有没有办法在 TypeScript 2+ 中全局添加类型定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆