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

Remix导入oslo/password时的polyfill问题求助

在Remix中使用oslo/password时解决构建报错问题

当在Remix应用中导入oslo/password实现认证功能时,构建出现以下错误:

✘ [ERROR] No matching export in "node-modules-polyfills:node:crypto" for import "scrypt"

node_modules/oslo/dist/password/scrypt.js:1:9:
  1 │ import { scrypt } from "node:crypto";
    ╵          ~~~~~~

这是因为oslo/password依赖Node.js原生crypto模块的scrypt方法,浏览器环境不支持该API,或Remix打包配置未正确区分服务器/客户端代码导致的。

解决方案

1. 确保密码操作仅在服务器端执行

密码哈希、验证这类敏感操作绝对不能在浏览器端运行,应将相关代码放在Remix的loader、action函数中,或仅在服务器端工具模块里导入oslo/password。

示例:在服务器路由的action中处理注册逻辑

// app/routes/api/register.ts
import { ActionFunctionArgs } from "@remix-run/node";
import { hash } from "oslo/password";

export async function action({ request }: ActionFunctionArgs) {
  const formData = await request.formData();
  const password = formData.get("password") as string;
  const hashedPassword = await hash(password);
  // 将哈希后的密码存入数据库...
  return new Response("注册成功");
}

2. 调整Remix配置文件

在remix.config.js中配置serverDependenciesToBundle,确保服务器端正确打包ESM-only的oslo模块:

/** @type {import('@remix-run/dev').AppConfig} */
export default {
  serverDependenciesToBundle: ["oslo", "oslo/password"],
  // 可选:设置服务器模块格式为ESM,提升与oslo的兼容性
  serverModuleFormat: "esm",
  // 保留原有其他配置...
};

3. 若需客户端兼容(不推荐)

如果确实有特殊需求要在客户端处理(不建议),可通过webpack添加crypto的polyfill:

  1. 安装依赖:
npm install crypto-browserify --save-dev
  1. 修改remix.config.js的webpack配置:
export default {
  // 保留原有其他配置...
  webpack: (config) => {
    config.resolve.fallback = {
      ...config.resolve.fallback,
      crypto: require.resolve("crypto-browserify"),
    };
    return config;
  },
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 20:35:11