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

Vue3导入jsonwebtoken报错:Cannot read properties of undefined (reading 'from')

解决Vite+TypeScript中jsonwebtoken导入报错的问题

问题根源

jsonwebtoken是为Node.js环境设计的库,依赖Node.js内置的buffer等模块,而Vite在浏览器构建时会将这类Node内置模块外部化,导致客户端运行时找不到相关依赖,从而抛出错误。


方案一:使用浏览器兼容的JWT库(推荐)

直接替换为专为浏览器环境设计的JWT处理库,比如jose或jsrsasign,无需依赖Node内置模块。

以jose为例:

  1. 安装依赖
npm install jose
  1. TypeScript中使用示例
import { SignJWT, jwtVerify } from 'jose';

// 生成JWT
async function createToken(payload: Record<string, any>, secret: string) {
  const encoder = new TextEncoder();
  return await new SignJWT(payload)
    .setProtectedHeader({ alg: 'HS256' })
    .setExpirationTime('1h')
    .sign(encoder.encode(secret));
}

// 验证JWT
async function checkToken(token: string, secret: string) {
  const encoder = new TextEncoder();
  const { payload } = await jwtVerify(token, encoder.encode(secret));
  return payload;
}

方案二:为jsonwebtoken配置Node模块Polyfill(不推荐生产环境)

如果一定要使用jsonwebtoken,可以通过Vite插件为浏览器环境提供Node内置模块的Polyfill:

  1. 安装依赖和插件
npm install buffer
npm install vite-plugin-node-polyfills --save-dev
  1. 修改vite.config.ts配置
import { defineConfig } from 'vite';
import { nodePolyfills } from 'vite-plugin-node-polyfills';

export default defineConfig({
  plugins: [
    nodePolyfills({
      include: ['buffer'],
      globals: {
        Buffer: true,
      },
    }),
  ],
});
  1. 正常导入使用jsonwebtoken
import jwt from 'jsonwebtoken';

// 生成token
const token = jwt.sign({ userId: 123 }, 'your-secret-key', { expiresIn: '1h' });
// 验证token
const decoded = jwt.verify(token, 'your-secret-key');

关于require语法的问题

Vite默认优先支持ES模块(import/export),无需使用require,按照上述方案配置后,直接用import即可正常导入。

内容的提问来源于stack exchange,提问作者Trần Phước Lộc

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 09:16:11