引用外部打字稿文件时如何避免“找不到模块:错误:无法解析‘tslib’"错误? [英] How to avoid "Module not found: Error: Can't resolve 'tslib'"-error when referencing an external typescript file?
问题描述
我有一个客户端/服务器应用程序,其中客户端是一个 angular-app.服务器确实为其提供的 API 提供了几个打字稿定义.这些定义是从项目外部文件夹加载的.到目前为止,这工作正常,但是现在我正在从 Angular 7 升级到 Angular 8(并且还将 Typescript 从 3.1 版升级到 3.5),并且当尝试使用定义中的非静态枚举时,现在会产生以下错误:
I have a client/server application, where the client is an angular-app. The server does provide a couple of typescript-definitions for the API it provides. These definitions are loaded from a project-external folder. So far this worked fine, however now I am upgrading from Angular 7 to Angular 8 (and with that also upgrading Typescript from Version 3.1 to 3.5) and when trying to use a non-static enum from the definitions, this now produces this error:
未找到模块:错误:无法解析/path/to/server/definitions"中的tslib"
Module not found: Error: Can't resolve 'tslib' in '/path/to/server/definitions'
当 api.ts
文件位于客户端目录中时,一切正常.
When the api.ts
-file is located within the client-dir, then everything works just fine.
为什么会发生这种情况,我能做些什么?
这是一个快速脚本来创建一个最小的例子来重现:
Here is a quick script to create a minimal example to reproduce:
mkdir project
cd project
ng new client --minimal=true --skipGit=true --routing=false --style=css
mkdir server
echo 'export enum ApiSample { X = "X" }' > server/api.ts
sed -i 's/"compilerOptions": {/"compilerOptions": {"paths":{"api":["..\/server\/api"]},/' client/tsconfig.json
sed -i -e "1iimport { ApiSample } from 'api';" -e "s/title = 'client';/title = 'client' + ApiSample.X;/" client/src/app/app.component.ts
cd client
npm start
或者,手动创建示例:
- 创建一个新的 Angular 项目
- 在文件系统的某处创建一个文件api.ts",内容为
export enum ApiSample { X = "X" }
- 在tsconfig.json"中添加
{"paths":{"api":["/path/to/server/api"]}
到compilerOptions
- 从 angular 项目的任何文件访问
ApiSample.X
- 运行
npm start
目前的发现
- 迁移者在 tsconfig.json 中添加了
"importHelpers": true
.这就是为什么它以前有效而现在不再有效的原因.在 tsconfig.json 中指定"importHelpers": false
解决了这个问题,但当然这个选项是有原因的,所以这不是最终的解决方案 - 显式指定
"tslib": ["node_modules/tslib"]
修复了问题.这可能是最终的解决方案,尽管了解究竟发生了什么以及记录在何处会很有趣. - The migrator added
"importHelpers": true
in tsconfig.json. That is why it worked before and is not working anymore now. Specifying"importHelpers": false
in tsconfig.json fixes the issue, but of course this option is there for a reason, so that is no final solution - Explicitly specifying
"tslib": ["node_modules/tslib"]
fixes the problem. This may be a final solution although it would be interesting to know what is exactly happening and where this is documented.
Findings so far
推荐答案
Angular 8&9
因此,对于 Angular 8 和 9,似乎在 tsconfig.json 中将 "tslib": ["node_modules/tslib"]
添加到 compilerOptions/paths
解决问题.
在 Angular 10 中,问题完全消失,不再需要解决方法.
In Angular 10 the problem disappeared altogether, no workaround is needed anymore.
这篇关于引用外部打字稿文件时如何避免“找不到模块:错误:无法解析‘tslib’"错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!