随着 Angular 版本的不断更新,开发者们常常会遇到一些与旧有库兼容性的问题,特别是当这些库采用 CommonJS 格式而 Angular 使用了新的编译器如 Vite 时。今天我们来探讨如何在 Angular 18 中正确导入和使用一个 CommonJS 模块——以 slayer
库为例。
问题背景
假设你正在使用 Angular 18,并且需要将一个没有类型定义文件(@types)的 CommonJS 库 slayer
集成到你的项目中。即使你已经在 tsconfig.json
和 tsconfig.app.json
中添加了 "types": ["node"]
,并在 type.d.ts
中声明了 declare module 'slayer';
,你仍然可能遇到类似 ReferenceError: process is not defined
的错误。
解决方案
让我们一步步解决这个问题:
1. 配置 tsconfig 文件
首先,确保你的 tsconfig.app.json
文件中包含以下配置: