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

TypeScript使用crypto模块报错,不知如何配置platform: 'node'

解决TypeScript中使用crypto模块的"built into node"报错

当你在TypeScript项目中引入Node.js内置的crypto模块时,出现如下报错:

The package "crypto" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use "platform: 'node'" to do that, which will remove this error.

这是因为你的打包工具(这里是esbuild,通过Cypress的esbuild预处理器使用)默认以浏览器平台为目标,无法识别Node.js内置模块。只需按以下步骤配置platform: 'node'即可解决:

1. 配置Cypress的esbuild预处理器

在你的cypress.config.ts(如果用JS则为cypress.config.js)中,添加esbuild的平台配置:

import { defineConfig } from "cypress";
import createEsbuildPlugin from "@bahmutov/cypress-esbuild-preprocessor";

export default defineConfig({
  e2e: {
    setupNodeEvents(on) {
      // 配置esbuild选项,指定平台为Node.js
      const esbuildOptions = {
        platform: "node",
      };
      on("file:preprocessor", createEsbuildPlugin({ esbuildOptions }));
    },
  },
});

2. 优化tsconfig.json配置(可选)

你的tsconfig.json中lib包含了dom,但crypto是Node.js模块,不需要浏览器DOM环境,建议修改lib字段:

{
  "compilerOptions": {
    "module": "Node16",
    "moduleResolution": "Node16",
    "target": "ES2022",
    "lib": ["ES2022"], // 移除dom,只保留ES标准库
    "types": ["cypress", "node"]
  },
  "include": ["**/*.ts"]
}

完成以上配置后,重新运行项目,crypto模块的报错就会消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 19:30:22