Skip to content

Commit 4609d13

Browse files
authored
Merge pull request #61 from electron-vite/v0.14.1
V0.14.1
2 parents 0e08cd6 + 431c2b9 commit 4609d13

File tree

5 files changed

+81
-47
lines changed

5 files changed

+81
-47
lines changed

CHANGELOG.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,10 @@
1+
## 0.14.1 (2023-04-15)
2+
3+
- ffef5f2 chore: bump vite-plugin-utils to 0.4.1
4+
- 7d8471e chore: add comments
5+
- 4d50e2f fix: better `.cjs` file import path #60
6+
- 274cf00 chore(v0.14.1): cleanup
7+
18
## 0.14.0 (2023-04-13)
29

310
#### Break!

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "vite-plugin-electron-renderer",
3-
"version": "0.14.0",
3+
"version": "0.14.1",
44
"description": "Support use Node.js API in Electron-Renderer",
55
"main": "./dist/index.js",
66
"types": "./dist/index.d.ts",
@@ -33,7 +33,7 @@
3333
"rollup": "^3.19.1",
3434
"typescript": "^5.0.2",
3535
"vite": "^4.2.0",
36-
"vite-plugin-utils": "^0.4.0",
36+
"vite-plugin-utils": "^0.4.1",
3737
"vitest": "^0.29.3"
3838
},
3939
"files": [

pnpm-lock.yaml

Lines changed: 4 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/cjs-shim.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ export default function cjsShim(): Plugin {
4747

4848
if (assetsDir) {
4949
// ---------------------------------------- shim-require-id
50+
// TODO: https://github.com/electron-vite/vite-plugin-electron-renderer/blob/v0.14.1/src/index.ts#L348-L349
5051
const requireIdShim = `<script id="shim-require-id">
5152
; (function () {
5253
if (typeof require !== 'function') return;

src/index.ts

Lines changed: 67 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,15 @@ import type {
77
Plugin as VitePlugin,
88
UserConfig,
99
} from 'vite'
10+
import { normalizePath } from 'vite'
1011
import esbuild from 'esbuild'
1112
import type { RollupOptions } from 'rollup'
1213
import libEsm from 'lib-esm'
13-
import { COLOURS, node_modules as find_node_modules } from 'vite-plugin-utils/function'
14+
import {
15+
COLOURS,
16+
node_modules as find_node_modules,
17+
relativeify,
18+
} from 'vite-plugin-utils/function'
1419

1520
const require = createRequire(import.meta.url)
1621
const builtins = builtinModules.filter(m => !m.startsWith('_'));
@@ -23,7 +28,7 @@ const CACHE_DIR = '.vite-electron-renderer'
2328

2429
const electron = `
2530
const electron = typeof require !== 'undefined'
26-
// All exports module see https://www.electronjs.org -> API -> Renderer Process Modules
31+
// All exports module see https://www.electronjs.org -> API -> Renderer process Modules
2732
? (function requireElectron() {
2833
const avoid_parse_require = require;
2934
return avoid_parse_require("electron");
@@ -108,31 +113,19 @@ export interface RendererOptions {
108113
}
109114

110115
export default function renderer(options: RendererOptions = {}): VitePlugin {
116+
let root: string
111117
let cacheDir: string
112-
const moduleCache = new Map<string, string>()
118+
const cwd = process.cwd()
113119
const resolveKeys: string[] = []
120+
const moduleCache = new Map<string, string>()
114121

115122
return {
116123
name: 'vite-plugin-electron-renderer',
117124
async config(config, { command }) {
118-
// Make sure that Electron can be loaded into the local file using `loadFile()` after package
119-
config.base ??= './'
120-
121-
config.build ??= {}
122-
config.build.rollupOptions ??= {}
125+
// https://github.com/vitejs/vite/blob/v4.2.1/packages/vite/src/node/config.ts#L469-L472
126+
root = normalizePath(config.root ? path.resolve(config.root) : cwd)
123127

124-
// Some third-party modules, such as `fs-extra`, it will extend the nativ fs module, maybe we need to stop it
125-
// ① Avoid freeze Object
126-
setOutputFreeze(config.build.rollupOptions)
127-
// ② Avoid not being able to set - https://github.com/rollup/plugins/blob/commonjs-v24.0.0/packages/commonjs/src/helpers.js#L55-L60
128-
withIgnore(config.build, electronBuiltins)
129-
130-
// ---------------------------------------------------------------------------------------------------
131-
132-
cacheDir = path.join(
133-
find_node_modules(config.root ?? process.cwd())?.[0] ?? process.cwd(),
134-
CACHE_DIR,
135-
)
128+
cacheDir = path.join(find_node_modules(root)[0] ?? cwd, CACHE_DIR)
136129

137130
for (const [key, option] of Object.entries(options.resolve ?? {})) {
138131
if (command === 'build' && option.type === 'esm') {
@@ -142,15 +135,6 @@ export default function renderer(options: RendererOptions = {}): VitePlugin {
142135
resolveKeys.push(key)
143136
}
144137

145-
config.optimizeDeps ??= {}
146-
config.optimizeDeps.exclude ??= []
147-
for (const key of resolveKeys) {
148-
if (!config.optimizeDeps.exclude.includes(key)) {
149-
// Avoid Vite secondary pre-bundle
150-
config.optimizeDeps.exclude.push(key)
151-
}
152-
}
153-
154138
// builtins
155139
const aliases: Alias[] = [{
156140
find: new RegExp(`^(?:node:)?(${['electron', ...builtins].join('|')})$`),
@@ -193,16 +177,21 @@ export default function renderer(options: RendererOptions = {}): VitePlugin {
193177
if (typeof resolved.build === 'function') {
194178
snippets = await resolved.build({
195179
cjs: module => Promise.resolve(getSnippets({ import: module, export: module })),
196-
esm: (module, buildOptions) => getPreBundleSnippets(
180+
esm: (module, buildOptions) => getPreBundleSnippets({
181+
root,
197182
module,
198-
cacheDir,
183+
outdir: cacheDir,
199184
buildOptions,
200-
),
185+
}),
201186
})
202187
} else if (resolved.type === 'cjs') {
203188
snippets = getSnippets({ import: source, export: source })
204189
} else if (resolved.type === 'esm') {
205-
snippets = await getPreBundleSnippets(source, cacheDir)
190+
snippets = await getPreBundleSnippets({
191+
root,
192+
module: source,
193+
outdir: cacheDir,
194+
})
206195
}
207196

208197
console.log(
@@ -240,10 +229,28 @@ export default function renderer(options: RendererOptions = {}): VitePlugin {
240229
// ② Use in Pre-Bundling - https://github.com/vitejs/vite/blob/v4.2.0/packages/vite/src/node/optimizer/esbuildDepPlugin.ts#L199
241230
// ③ Worker does not share plugins - https://github.com/vitejs/vite/blob/v4.2.0/packages/vite/src/node/config.ts#L253-L256
242231
modifyAlias(config, aliases)
232+
233+
modifyOptimizeDeps(config, resolveKeys)
234+
235+
adaptElectron(config)
243236
},
244237
}
245238
}
246239

240+
function adaptElectron(config: UserConfig) {
241+
// Make sure that Electron can be loaded into the local file using `loadFile()` after package
242+
config.base ??= './'
243+
244+
config.build ??= {}
245+
config.build.rollupOptions ??= {}
246+
247+
// Some third-party modules, such as `fs-extra`, it will extend the nativ fs module, maybe we need to stop it
248+
// ① Avoid freeze Object
249+
setOutputFreeze(config.build.rollupOptions)
250+
// ② Avoid not being able to set - https://github.com/rollup/plugins/blob/commonjs-v24.0.0/packages/commonjs/src/helpers.js#L55-L60
251+
withIgnore(config.build, electronBuiltins)
252+
}
253+
247254
function setOutputFreeze(rollupOptions: RollupOptions) {
248255
rollupOptions.output ??= {}
249256
if (Array.isArray(rollupOptions.output)) {
@@ -275,6 +282,17 @@ function withIgnore(configBuild: BuildOptions, modules: string[]) {
275282
}
276283
}
277284

285+
function modifyOptimizeDeps(config: UserConfig, exclude: string[]) {
286+
config.optimizeDeps ??= {}
287+
config.optimizeDeps.exclude ??= []
288+
for (const str of exclude) {
289+
if (!config.optimizeDeps.exclude.includes(str)) {
290+
// Avoid Vite secondary pre-bundle
291+
config.optimizeDeps.exclude.push(str)
292+
}
293+
}
294+
}
295+
278296
function modifyAlias(config: UserConfig, aliases: Alias[]) {
279297
config.resolve ??= {}
280298
config.resolve.alias ??= []
@@ -299,11 +317,19 @@ function getSnippets(module: {
299317
return `const avoid_parse_require = require; const _M_ = avoid_parse_require("${module.export}");\n${exports}`
300318
}
301319

302-
async function getPreBundleSnippets(
303-
module: string,
304-
outdir: string,
305-
buildOptions: esbuild.BuildOptions = {},
306-
) {
320+
async function getPreBundleSnippets(options: {
321+
root: string
322+
module: string
323+
outdir: string
324+
buildOptions?: esbuild.BuildOptions
325+
}) {
326+
const {
327+
root,
328+
module,
329+
outdir,
330+
buildOptions = {},
331+
} = options
332+
307333
const outfile = path.join(outdir, module) + '.cjs'
308334
await esbuild.build({
309335
entryPoints: [module],
@@ -319,9 +345,9 @@ async function getPreBundleSnippets(
319345

320346
return getSnippets({
321347
import: outfile,
322-
// 🐞 `require("./${module}.cjs")` can not works under the `import`,
323-
// the `require("${CACHE_DIR}/${module}.cjs")` to represent the bare-module in `node_modules`
324-
export: `${CACHE_DIR}/${module}.cjs`,
348+
// Since any module will be imported as an `import` in the Renderer process,
349+
// the __dirname(import.meta.url) of the module should be http://localhost:5173/ which is the `root` directory
350+
export: relativeify(path.posix.relative(root, outfile)),
325351
})
326352
}
327353

0 commit comments

Comments
 (0)