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

Electron/Vite项目构建后出现模块找不到问题求助

Electron/Vite 构建后模块找不到及类型错误解决方案

问题概述

构建 Electron/Vite 项目后出现以下问题:

  • 报错无法找到 newMessageHandler、axios、crypto 模块
  • 改用 path.join(__dirname, 'events/newMessage.js') 引入后,触发 newMessage/axios/crypto 不是函数的错误
  • 已安装相关依赖,但不清楚如何将 events 目录及依赖纳入构建

用户提供代码

主进程代码

const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const newMessageHandler = require('./events/newMessage.js');
const axios = require('axios')
const crypto = require('crypto')
const isDev = !app.isPackaged;

Vite 配置

export default defineConfig({
  plugins: [react()],
  build: {
    outDir: 'dist',
  },
  base: './', // Set base to './'
});

分步解决方案

1. 修正主进程文件路径

Electron 打包后 __dirname 指向会改变,改用 app.getAppPath() 获取应用根目录来构建绝对路径:

const newMessageHandler = require(path.join(app.getAppPath(), 'events/newMessage.js'));

2. 配置 Vite 处理主进程代码

Vite 默认仅处理渲染进程,需在配置中指定主进程入口,确保依赖被正确打包:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';

export default defineConfig({
  plugins: [react()],
  build: {
    outDir: 'dist',
    rollupOptions: {
      input: {
        main: path.resolve(__dirname, 'main.js'), // 替换为你的主进程入口文件路径
      },
    },
  },
  base: './',
});

3. 处理 crypto 模块

crypto 是 Node.js 内置模块,无需额外安装:

  • 主进程中直接 require('crypto') 即可使用
  • 若在渲染进程使用,需在预加载脚本中通过 contextBridge 安全暴露:
// preload.js
const { contextBridge } = require('electron');
const crypto = require('crypto');

contextBridge.exposeInMainWorld('electronCrypto', {
  createHash: (algo, data) => crypto.createHash(algo).update(data).digest('hex'),
  // 按需暴露其他所需方法
});

4. 确保 axios 正确打包

  • 确认 axios 安装在 dependencies 而非 devDependencies 中:
npm install axios --save
  • 主进程中直接 require('axios');渲染进程建议用 ES 模块引入:import axios from 'axios'

5. 纳入 events 目录到构建

  • 主进程使用的 events 目录文件,只要通过主进程入口正确引入,Vite 会自动将其纳入打包
  • 若为渲染进程使用,需确保文件路径正确,或在 Vite 的 rollupOptions.input 中添加对应入口

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 02:35:07