Use Electron and NodeJs API in Renderer-process | 简体中文
Usage
vite.config.ts
import { defineConfig } from 'vite'
import electron from 'vite-plugin-electron-renderer'
export default defineConfig({
plugins: [
electron(),
],
})
vrenderer/foo.ts
import { ipcRenderer } from 'electron'
ipcRenderer.on('event-name', () => {
})
Options.resolve
In some cases, you just want "vite" to load a module like NodeJs.
You can custom-resolve the module eg:
vite.config.ts
import { defineConfig } from 'vite'
import electron from 'vite-plugin-electron-renderer'
export default defineConfig({
plugins: [
electron({
resolve: {
'electron-store': `const Store=require('electron-store'); export default Store;`;
sqlite3: () => {
const sqlite3 = require('sqlite3');
const members = Object.keys(sqlite3);
const code = `
const sqlite3 = require("sqlite3");
const { ${members.join(', ')} } = sqlite3;
export { ${members.join(', ')}, sqlite3 as default }
`;
return code;
},
},
}),
],
})
How to work
- Fist, the plugin will configuration something.
-
If you do not configure the following options, the plugin will modify their default values
base = './'
build.assetsDir = ''
build.rollupOptions.output.format = 'cjs'
-
Add "electron", NodeJs built-in modules and "options.resolve" to "optimizeDeps.exclude"
{
optimizeDeps: {
exclude: [
'electron',
...'built-in modules',
...Object.keys(options.resolve),
],
},
}
-
The plugin transform "electron" and NodeJs built-in modules to ESModule format in "vite serve" phase.
-
Add "electron" and NodeJs built-in modules to Rollup "output.external" option in the "vite build" phase.
Using electron in Renderer-process import { ipcRenderer } from 'electron
Actually redirect to "node_modules/vite-plugin-electron-renderer/modules/electron-renderer.js" through "resolve.alias".