You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Angular 13迁移到18后,如何正确导入CommonJS库slayer?

解决Angular 18(Vite)中导入CommonJS库slayer的process未定义问题

核心原因

Angular 18切换到Vite编译器后,默认在浏览器环境中不会提供Node.js的全局变量(如process),而slayer依赖的readable-stream库直接使用了该变量,导致报错。

解决方案步骤

1. 安装Node.js全局变量polyfill插件

执行以下命令安装适配Vite的Node.js polyfill工具:

npm install vite-plugin-node-polyfills --save-dev

2. 配置Vite插件到Angular项目

修改项目根目录下的angular.json,找到projects -> [你的项目名] -> architect -> build -> options,添加vitePlugins配置;同时在serve -> options中同步添加:

"build": {
  "builder": "@angular-devkit/build-angular:application",
  "options": {
    // ... 其他原有配置
    "vitePlugins": [
      {
        "name": "vite-plugin-node-polyfills",
        "options": {
          "globals": {
            "process": true // 模拟process全局变量
          },
          "polyfills": [
            "stream" // 为readable-stream提供polyfill
          ]
        }
      }
    ]
  }
},
"serve": {
  "builder": "@angular-devkit/build-angular:dev-server",
  "options": {
    // ... 其他原有配置
    "vitePlugins": [
      {
        "name": "vite-plugin-node-polyfills",
        "options": {
          "globals": {
            "process": true
          },
          "polyfills": [
            "stream"
          ]
        }
      }
    ]
  }
}

3. 确保类型声明正确保留

保留你已创建的type.d.ts文件,内容如下即可(如果需要更详细的类型,可以根据slayer的API自行补充):

declare module 'slayer';

4. 验证配置并重启开发服务

停止当前运行的开发服务器,执行ng serve重启,检查是否仍有报错。如果问题依旧,可以尝试:

  • 在tsconfig.app.json中添加"allowJs": true,确保CommonJS模块能被正确转译
  • 清理node_modules和构建缓存:rm -rf node_modules && npm install && ng cache clean

内容的提问来源于stack exchange,提问作者Brett

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 03:33:16