windows - Vite-electron configuration for own js logic code - Stack Overflow

时间: 2025-01-06 admin 业界

I am new to electron-vite with react. My project has a http node server process. All related files are place in server named folder. The vite folder structure is main, renderer and preload. I have placed server folder in src, that means it is main, renderer, preload and server folder. server.js is there in server folder. Below is the line of code which fails

serverProcess = fork(path.join(__dirname, '../sync/server.js'), {
    env: { PORT: 9090 }
  })

it fails with, Cannot find module 'D:\codebase\syncer\out\server\server.js package.json has "main": "./out/main/index.js", It tries to find the server code in out folder. I don't know what to mention (configuration) to use all folder and files in server folder. The platform is windows 11. please help me.

I am new to electron-vite with react. My project has a http node server process. All related files are place in server named folder. The vite folder structure is main, renderer and preload. I have placed server folder in src, that means it is main, renderer, preload and server folder. server.js is there in server folder. Below is the line of code which fails

serverProcess = fork(path.join(__dirname, '../sync/server.js'), {
    env: { PORT: 9090 }
  })

it fails with, Cannot find module 'D:\codebase\syncer\out\server\server.js package.json has "main": "./out/main/index.js", It tries to find the server code in out folder. I don't know what to mention (configuration) to use all folder and files in server folder. The platform is windows 11. please help me.

Share Improve this question asked yesterday skyconfusionskyconfusion 1238 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

One approach is copying the server folder into the final build using extraResources in the electron-builder config:

"build": {
  "extraResources": [
    { "from": "server", "to": "server" }
  ]
}

The script can then be referenced by checking if it’s development or production:

const isDev = process.env.NODE_ENV === 'development';
const serverPath = isDev
  ? path.join(__dirname, '../server/server.js')
  : path.join(process.resourcesPath, 'server', 'server.js');

const serverProcess = fork(serverPath, { env: { PORT: 9090 } });

That way, server.js is included in the build, preventing the “Cannot find module” error.