Skip to content

Commit 97e8e3e

Browse files
authored
Merge pull request #26 from electron-vite/v0.12.0
V0.12.0
2 parents 4ef703c + f558983 commit 97e8e3e

14 files changed

+417
-257
lines changed

CHANGELOG.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,13 @@
1+
## 0.12.0 (2023-02-09)
2+
3+
#### Main Changed
4+
5+
- c97bd16 refactor: better builtins build
6+
- 61e9e05 refactor: better polyfill with `nodeIntegration:false` #24
7+
- 4ef703c feat: lazy load `esbuild`
8+
- 06e7f31 Merge pull request #25 from electron-vite/vitest
9+
- 35bb551 feat(test): integrate vitest
10+
111
## 0.11.4 (2023-01-04)
212

313
- 502f7f2 feat: support Pre-Bundling cache #15

README.md

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,30 @@
1-
# vite-plugin-electron-renderer
2-
3-
Support use Node.js API in Electron-Renderer
4-
5-
[![NPM version](https://img.shields.io/npm/v/vite-plugin-electron-renderer.svg)](https://npmjs.org/package/vite-plugin-electron-renderer)
6-
[![NPM Downloads](https://img.shields.io/npm/dm/vite-plugin-electron-renderer.svg)](https://npmjs.org/package/vite-plugin-electron-renderer)
7-
8-
English | [简体中文](https://github.com/electron-vite/vite-plugin-electron-renderer/blob/main/README.zh-CN.md)
1+
<p align="center">
2+
<img width="170" src="https://github.com/electron-vite/vite-plugin-electron/blob/main/logo.svg?raw=true">
3+
</p>
4+
<div align="center">
5+
<h1>vite-plugin-electron-renderer</h1>
6+
</div>
7+
<p align="center">Support use Node.js API in Electron-Renderer</p>
8+
<p align="center">
9+
<a href="https://npmjs.com/package/vite-plugin-electron-renderer">
10+
<img src="https://img.shields.io/npm/v/vite-plugin-electron-renderer.svg">
11+
</a>
12+
<a href="https://npmjs.com/package/vite-plugin-electron-renderer">
13+
<img src="https://img.shields.io/npm/dm/vite-plugin-electron-renderer.svg">
14+
</a>
15+
<a href="https://discord.gg/YfjFuEgVUR">
16+
<img src="https://img.shields.io/badge/chat-discord-blue?logo=discord">
17+
</a>
18+
</p>
19+
<p align="center">
20+
<strong>
21+
<span>English</span>
22+
|
23+
<a href="https://github.com/electron-vite/vite-plugin-electron-renderer/blob/main/README.zh-CN.md">简体中文</a>
24+
</strong>
25+
</p>
26+
27+
<br/>
928

1029
## Install
1130

@@ -15,6 +34,7 @@ npm i vite-plugin-electron-renderer -D
1534

1635
## Examples
1736

37+
- [electron-forge](https://github.com/electron-vite/vite-plugin-electron-renderer/tree/main/examples/electron-forge) - use in [Electron Forge](https://www.electronforge.io/) scaffolds.
1838
- [quick-start](https://github.com/electron-vite/vite-plugin-electron-renderer/tree/main/examples/quick-start)
1939
- [worker](https://github.com/electron-vite/vite-plugin-electron-renderer/tree/main/examples/worker)
2040

File renamed without changes.
File renamed without changes.
File renamed without changes.

builtins.mjs

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import fs from 'node:fs'
2+
import path from 'node:path'
3+
import { builtinModules } from 'node:module'
4+
import { fileURLToPath } from 'node:url'
5+
import libEsm from 'lib-esm'
6+
7+
var __dirname = path.dirname(fileURLToPath(import.meta.url))
8+
9+
export const builtins = builtinModules.filter(m => !m.startsWith('_'))
10+
export const builtins_dir = path.join(__dirname, 'builtins')
11+
export const electron = `
12+
const electron = typeof require !== 'undefined'
13+
// All exports module see https://www.electronjs.org -> API -> Renderer Process Modules
14+
? require("electron")
15+
: (function nodeIntegrationWarn() {
16+
console.error(\`If you need to use "electron" in the Renderer process, make sure that "nodeIntegration" is enabled in the Main process.\`)
17+
return {
18+
// TODO: polyfill
19+
};
20+
}());
21+
22+
// Proxy in Worker
23+
let _ipcRenderer;
24+
if (typeof document === 'undefined') {
25+
_ipcRenderer = {};
26+
const keys = [
27+
'invoke',
28+
'postMessage',
29+
'send',
30+
'sendSync',
31+
'sendTo',
32+
'sendToHost',
33+
// propertype
34+
'addListener',
35+
'emit',
36+
'eventNames',
37+
'getMaxListeners',
38+
'listenerCount',
39+
'listeners',
40+
'off',
41+
'on',
42+
'once',
43+
'prependListener',
44+
'prependOnceListener',
45+
'rawListeners',
46+
'removeAllListeners',
47+
'removeListener',
48+
'setMaxListeners',
49+
];
50+
for (const key of keys) {
51+
_ipcRenderer[key] = () => {
52+
throw new Error(
53+
'ipcRenderer doesn\\'t work in a Web Worker.\\n' +
54+
'You can see https://github.com/electron-vite/vite-plugin-electron/issues/69'
55+
);
56+
};
57+
}
58+
} else {
59+
_ipcRenderer = electron.ipcRenderer;
60+
}
61+
62+
export { electron as default };
63+
export const clipboard = electron.clipboard;
64+
export const contextBridge = electron.contextBridge;
65+
export const crashReporter = electron.crashReporter;
66+
export const ipcRenderer = _ipcRenderer;
67+
export const nativeImage = electron.nativeImage;
68+
export const shell = electron.shell;
69+
export const webFrame = electron.webFrame;
70+
export const deprecate = electron.deprecate;
71+
`.trim()
72+
73+
export async function generateBuiltins() {
74+
fs.rmSync(builtins_dir, { recursive: true, force: true })
75+
76+
// Node.js
77+
for (const module of builtins) {
78+
const filename = path.join(builtins_dir, module) + '.js'
79+
const dirname = path.dirname(filename)
80+
!fs.existsSync(dirname) && fs.mkdirSync(dirname, { recursive: true })
81+
82+
// [2023-03-09] `import('trace_events')` in [email protected] causes an error
83+
// Error: Trace events are unavailable
84+
// ❯ node:trace_events:25:9
85+
86+
const { exports } = libEsm({ exports: Object.keys(await import(module)) })
87+
fs.writeFileSync(filename, `const _M_ = require("${module}");\n${exports}`)
88+
}
89+
90+
// Electron
91+
fs.writeFileSync(path.join(builtins_dir, 'electron.js'), electron)
92+
93+
console.log('[builtins] build success.\n')
94+
}

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "vite-plugin-electron-renderer",
3-
"version": "0.11.4",
3+
"version": "0.12.0",
44
"description": "Support use Node.js API in Electron-Renderer",
55
"main": "index.mjs",
66
"types": "types",

src/build-config.ts

Lines changed: 74 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
import { builtinModules } from 'node:module'
2-
import type { Plugin } from 'vite'
2+
import type {
3+
Alias,
4+
Plugin,
5+
UserConfig,
6+
} from 'vite'
37
import type { ExternalOption, RollupOptions } from 'rollup'
48

59
export const builtins = [
@@ -8,34 +12,64 @@ export const builtins = [
812
...builtinModules.filter(m => !m.startsWith('_')).map(mod => `node:${mod}`),
913
]
1014

11-
export default function buildConfig(nodeIntegration?: boolean): Plugin {
12-
return {
13-
name: 'vite-plugin-electron-renderer:build-config',
14-
apply: 'build',
15-
config(config) {
16-
// Make sure that Electron can be loaded into the local file using `loadFile` after packaging
17-
config.base ??= './'
15+
export default function buildConfig(nodeIntegration?: boolean): Plugin[] {
16+
return [
17+
{
18+
name: 'vite-plugin-electron-renderer:builtins',
19+
config(config) {
20+
const aliases: Alias[] = [
21+
// Always polyfill electron.
22+
{
23+
find: 'electron',
24+
replacement: 'vite-plugin-electron-renderer/builtins/electron',
25+
},
26+
...(nodeIntegration ? builtins
27+
.filter(m => m !== 'electron')
28+
.filter(m => !m.startsWith('node:'))
29+
.map<Alias>(m => ({
30+
find: new RegExp(`^(node:)?${m}$`),
31+
replacement: `vite-plugin-electron-renderer/builtins/${m}`,
32+
})) : []),
33+
]
1834

19-
config.build ??= {}
35+
modifyAlias(config, aliases)
36+
modifyOptimizeDeps(
37+
config,
38+
[
39+
'electron',
40+
'vite-plugin-electron-renderer/builtins/electron',
41+
].concat(nodeIntegration ? aliases.map(({ replacement }) => replacement) : []),
42+
)
43+
},
44+
},
45+
{
46+
name: 'vite-plugin-electron-renderer:build-config',
47+
apply: 'build',
48+
config(config) {
49+
// Make sure that Electron can be loaded into the local file using `loadFile` after packaging
50+
config.base ??= './'
2051

21-
// TODO: init `config.build.target`
22-
// https://github.com/vitejs/vite/pull/8843
52+
config.build ??= {}
2353

24-
// https://github.com/electron-vite/electron-vite-vue/issues/107
25-
config.build.cssCodeSplit ??= false
54+
// TODO: init `config.build.target`
55+
// https://github.com/vitejs/vite/pull/8843
2656

27-
// TODO: compatible with custom assetsDir
28-
// This will guarantee the proper loading of static resources, such as images, `worker.js`
29-
// The `.js` file can be loaded correctly with cjs-shim.ts
30-
config.build.assetsDir ??= ''
57+
// https://github.com/electron-vite/electron-vite-vue/issues/107
58+
config.build.cssCodeSplit ??= false
3159

32-
if (nodeIntegration) {
33-
config.build.rollupOptions ??= {}
34-
config.build.rollupOptions.external = withExternal(config.build.rollupOptions.external)
35-
setOutputFormat(config.build.rollupOptions)
36-
}
60+
// TODO: compatible with custom assetsDir
61+
// This will guarantee the proper loading of static resources, such as images, `worker.js`
62+
// The `.js` file can be loaded correctly with cjs-shim.ts
63+
config.build.assetsDir ??= ''
64+
65+
if (nodeIntegration) {
66+
config.build.rollupOptions ??= {}
67+
config.build.rollupOptions.external = withExternal(config.build.rollupOptions.external)
68+
setOutputFormat(config.build.rollupOptions)
69+
}
70+
},
3771
},
38-
}
72+
]
3973
}
4074

4175
function withExternal(external?: ExternalOption) {
@@ -71,3 +105,20 @@ function setOutputFormat(rollupOptions: RollupOptions) {
71105
rollupOptions.output.format ??= 'cjs'
72106
}
73107
}
108+
109+
export function modifyOptimizeDeps(config: UserConfig, exclude: string[]) {
110+
config.optimizeDeps ??= {}
111+
config.optimizeDeps.exclude ??= []
112+
config.optimizeDeps.exclude.push(...exclude)
113+
}
114+
115+
export function modifyAlias(config: UserConfig, aliases: Alias[]) {
116+
config.resolve ??= {}
117+
config.resolve.alias ??= []
118+
if (Object.prototype.toString.call(config.resolve.alias) === '[object Object]') {
119+
config.resolve.alias = Object
120+
.entries(config.resolve.alias)
121+
.reduce<Alias[]>((memo, [find, replacement]) => memo.concat({ find, replacement }), [])
122+
}
123+
(config.resolve.alias as Alias[]).push(...aliases)
124+
}

0 commit comments

Comments
 (0)