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

Node.js 22+Angular 18中crypto模块找不到问题求助

问题:Angular项目中无法解析内置模块'crypto',启动调试时报错

调试时始终出现如下错误:

Error: Module not found: Error: Can't resolve 'crypto' in ....

已尝试过以下操作,均无效:

  • npm update
  • ng update

我的后台认证服务代码(auth.service.ts,非浏览器端HTML组件)如下:

import { Injectable } from '@angular/core';
import { scrypt, randomBytes, timingSafeEqual } from "crypto";

const keyLength = 32;

@Injectable({
  providedIn: 'root'
})
export class AuthService {

constructor() {};

async login( username: string, password: string ) {
  if ( await AuthService.compare(username, await AuthService.hash(password))) {
    localStorage.setItem('STATE', 'true');
    return true;
  }

  return false;
}
  
async logout() {
    localStorage.setItem('STATE', 'false');

    return true;
}
  
isLoggedIn() {
  const loggedIn = localStorage.getItem('STATE');
  if (loggedIn == 'true')
    return true;
  else
    return false;
}

/**
 * 用scrypt哈希算法加密密码或密钥
 * @param {string} password
 * @returns {string} 盐值+哈希值
 */
static async hash( password: string ): Promise<string> {
  return new Promise((resolve, reject) => {
      // 生成16字节随机盐值 - NodeJS文档推荐
      const salt = randomBytes(16).toString("hex");

      scrypt(password, salt, keyLength, (err, derivedKey) => {
          if (err) reject(err);
          // derivedKey为Buffer类型
          resolve(`${salt}.${derivedKey.toString("hex")}`);
      });
    });
  };

/**
* 对比明文密码与盐值+哈希值
* @param {string} password 明文密码
* @param {string} hash 待验证的盐值+哈希值
* @returns {boolean}
*/
static async compare( password: string, hash: string ): Promise<boolean> {
  return new Promise((resolve, reject) => {
      const [salt, hashKey] = hash.split(".");
      // 需要传入Buffer类型值到timingSafeEqual
      const hashKeyBuff = Buffer.from(hashKey, "hex");
      scrypt(password, salt, keyLength, (err, derivedKey) => {
          if (err) reject(err);
          // 用timingSafeEqual对比新生成的哈希值与原哈希值
          resolve(timingSafeEqual(hashKeyBuff, derivedKey));
      });
    });
  };

}

当前使用Node.js 22.4.1版本,crypto是内置模块,但启动调试时仍报错,以下方案均不适用:

  • npm install crypto(旧安装方式)
  • 使用Crypto-JS替代
  • VS Code编辑器中无报错,仅调试运行时出现问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 00:07:03