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

Vue3项目导入@project-serum/anchor出现require未定义报错如何解决

报错原因

该错误是*@project-serum/anchor*依赖的js-sha256包内部使用了Node.js专属的CommonJS规范require语法,而Vue3前端项目运行在浏览器环境,浏览器原生不支持require语法,同时你的项目打包工具(Webpack/Vite)默认没有对该依赖做语法兼容转换,导致运行时识别不了require抛出异常。

解决方案

根据你使用的构建工具选择对应处理方案:

场景1:项目使用Vite构建

  • 安装vite-plugin-commonjs插件,用来把CommonJS模块转成浏览器可识别的ES模块:
npm install vite-plugin-commonjs -D
# 或者yarn安装
yarn add vite-plugin-commonjs -D
  • 修改vite.config.js配置,新增插件配置,同时将@project-serum/anchor加入预构建依赖列表:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import commonjs from 'vite-plugin-commonjs'

export default defineConfig({
  plugins: [vue(), commonjs()],
  optimizeDeps: {
    include: ['@project-serum/anchor']
  }
})
  • 如果修改后仍报错,可新增alias配置直接指向浏览器适配版的anchor:
resolve: {
  alias: {
    '@project-serum/anchor': '@project-serum/anchor/dist/browser/index.js'
  }
}

场景2:项目使用Vue CLI(Webpack)构建

  • 修改vue.config.js配置,把@project-serum/anchor和js-sha256加入转译依赖列表,让babel对这两个依赖做语法转换:
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: ['@project-serum/anchor', 'js-sha256']
})
  • 若仍有问题,可在项目入口文件(通常是main.js)顶部直接引入浏览器版的anchor:
import '@project-serum/anchor/dist/browser/index.js'

兜底方案

如果以上方法都不生效,可以直接用CDN方式引入anchor,避免打包转换问题:在public/index.html的head标签中加入对应script标签引入anchor资源即可,使用时直接访问全局anchor对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 05:36:03