@tomjs/vite-plugin-electron 1.5.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -96,7 +96,7 @@ import { app, BrowserWindow } from 'electron';
96
96
  global.__dirname = dirname(fileURLToPath(import.meta.url));
97
97
 
98
98
  const preload = join(__dirname, '../preload/index.mjs');
99
- const url = process.env.APP_DEV_SERVER_URL;
99
+ const url = process.env.VITE_DEV_SERVER_URL;
100
100
 
101
101
  async function createWindow() {
102
102
  win = new BrowserWindow({
@@ -126,14 +126,12 @@ Take using `esm` as an example, but it requires Electron>=28
126
126
 
127
127
  - `package.json`
128
128
 
129
- Electron `preload process` must use the `.mjs` suffix, otherwise an error will be reported, see [official documentation](https://www.electronjs.org/zh/docs/latest/tutorial/esm). So the default output of `esm` of `preload` uses the `.mjs` suffix.
130
-
131
- When the suffix of Electron `main process` is `.mjs` or `.cjs`, vscode breakpoint debugging cannot work, so the suffix defaults to `.js`.
129
+ Electron `preload process` must use the `.mjs` suffix, otherwise an error will be reported, see [official documentation](https://www.electronjs.org/zh/docs/latest/tutorial/esm). So the default output of `esm` of `preload` uses the `.mjs` suffix. For consistency, `main process` also ends with `.mjs`
132
130
 
133
131
  ```json
134
132
  {
135
133
  "type": "module",
136
- "main": "dist/main/index.js"
134
+ "main": "dist/main/index.mjs"
137
135
  }
138
136
  ```
139
137
 
@@ -203,9 +201,9 @@ export default defineConfig({
203
201
  | external | `string[]` | | Don't bundle these modules, but dependencies and peerDependencies in your package.json are always excluded.[See more](https://tsup.egoist.dev/#excluding-packages) |
204
202
  | main | [MainOptions](#MainOptions) | | Configuration options for the electron main process. |
205
203
  | preload | [PreloadOptions](#PreloadOptions) | | Configuration options for the electron preload process. |
206
- | debug | `boolean` | `false` | Electron debug mode, don't startup electron. You can also use `process.env.APP_ELECTRON_DEBUG`. Default is false. |
207
- | builder | `boolean` \| [BuilderOptions](#BuilderOptions) | `false` | If it is a `boolean` type, whether to enable [electron-builder](https://www.electron.build). If it is an object, it is the [configuration](https://www.electron.build/configuration/configuration) of [electron-builder](https://www.electron.build). You can also turn it on using `process.env.APP_ELECTRON_DEBUG`. |
208
- | inspect | `boolean` | `false` | Electron will listen for V8 inspector protocol messages on the specified port, an external debugger will need to connect on this port. You can also use `process.env.APP_ELECTRON_INSPECT`. See [debugging-main-process](https://www.electronjs.org/docs/latest/tutorial/debugging-main-process) for more information. |
204
+ | debug | `boolean` | `false` | Electron debug mode, don't startup electron. You can also use `process.env.VITE_ELECTRON_DEBUG`. Default is false. |
205
+ | builder | `boolean` \| [BuilderOptions](#BuilderOptions) | `false` | If it is a `boolean` type, whether to enable [electron-builder](https://www.electron.build). If it is an object, it is the [configuration](https://www.electron.build/configuration/configuration) of [electron-builder](https://www.electron.build). You can also turn it on using `process.env.VITE_ELECTRON_DEBUG`. |
206
+ | inspect | `boolean` | `false` | Electron will listen for V8 inspector protocol messages on the specified port, an external debugger will need to connect on this port. You can also use `process.env.VITE_ELECTRON_INSPECT`. See [debugging-main-process](https://www.electronjs.org/docs/latest/tutorial/debugging-main-process) for more information. |
209
207
 
210
208
  **Notice**
211
209
 
@@ -237,7 +235,7 @@ Based on [Options](https://paka.dev/npm/tsup) of [tsup](https://tsup.egoist.dev/
237
235
  | outDir | `string` | "dist-electron/preload" | The output directory for the preload process files |
238
236
  | onSuccess | `() => Promise<void \| undefined \| (() => void \| Promise<void>)>` | `undefined` | A function that will be executed after the build succeeds. |
239
237
 
240
- # BuilderOptions
238
+ ### BuilderOptions
241
239
 
242
240
  When `recommended` and `builder.enable` are both `true`, use [electron-builder](https://www.electron.build) to package Electron applications.
243
241
 
@@ -302,6 +300,24 @@ const config = {
302
300
  | sourcemap | `true` | `false` |
303
301
  | minify | `false` | `true` |
304
302
 
303
+ ## Environment Variables
304
+
305
+ ### Vite plugin variables
306
+
307
+ | Variable | Description |
308
+ | --- | --- |
309
+ | `VITE_ELECTRON_DEBUG` | Electron main process debug, don't startup electron. When value is true or 1 to enable, false or 0 to disable.Default is undefined. |
310
+ | `VITE_ELECTRON_INSPECT` | Electron will listen for V8 inspector protocol messages on the specified port, an external debugger will need to connect on this port. When value is true, the default port is 5858. |
311
+ | `VITE_ELECTRON_BUILDER` | Enable [electron-builder](https://www.electron.build) to package. When value is true or 1 to enable, false or 0 to disable. Default is undefined. |
312
+
313
+ ### Application variables
314
+
315
+ Electron `main process` and `renderer process` use.
316
+
317
+ | Variable | Description |
318
+ | --------------------- | -------------------------- |
319
+ | `VITE_DEV_SERVER_URL` | The url of the dev server. |
320
+
305
321
  ## Debug
306
322
 
307
323
  ### Web debugging
@@ -330,16 +346,7 @@ app.whenReady().then(() => {
330
346
  });
331
347
  ```
332
348
 
333
- ### Main thread debugging
334
-
335
- #### Turn on debugging
336
-
337
- Start code compilation through the following configuration or `ELECTRON_DEBUG=1 vite dev`
338
-
339
- - Enable by setting `APP_ELECTRON_DEBUG=1` in `.env.development` file
340
- - `vite.config.js` configures `electron({ debug: true })` to be turned on
341
-
342
- #### VSCODE
349
+ ### Main Process Debug
343
350
 
344
351
  Run `Debug Main Process` through `vscode` to debug the main thread. For debugging tools, refer to [Official Documentation](https://code.visualstudio.com/docs/editor/debugging)
345
352
 
@@ -351,6 +358,7 @@ Run `Debug Main Process` through `vscode` to debug the main thread. For debuggin
351
358
  "configurations": [
352
359
  {
353
360
  "name": "Debug Main Process",
361
+ "preLaunchTask": "npm:debug",
354
362
  "type": "node",
355
363
  "request": "launch",
356
364
  "cwd": "${workspaceFolder}",
@@ -359,8 +367,52 @@ Run `Debug Main Process` through `vscode` to debug the main thread. For debuggin
359
367
  "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd"
360
368
  },
361
369
  "args": ["."],
370
+ "outFiles": [
371
+ "${workspaceFolder}/**/*.js",
372
+ "${workspaceFolder}/**/*.cjs",
373
+ "${workspaceFolder}/**/*.mjs",
374
+ "!**/node_modules/**"
375
+ ],
362
376
  "envFile": "${workspaceFolder}/node_modules/@tomjs/vite-plugin-electron/debug/.env"
363
377
  }
364
378
  ]
365
379
  }
366
380
  ```
381
+
382
+ `tasks.json` is configured as follows:
383
+
384
+ ```json
385
+ {
386
+ "version": "2.0.0",
387
+ "tasks": [
388
+ {
389
+ "label": "npm:debug",
390
+ "type": "npm",
391
+ "script": "debug",
392
+ "detail": "cross-env VITE_ELECTRON_DEBUG=1 vite",
393
+ "isBackground": true,
394
+ "problemMatcher": {
395
+ "owner": "typescript",
396
+ "fileLocation": "relative",
397
+ "pattern": {
398
+ "regexp": "^([a-zA-Z]\\:/?([\\w\\-]/?)+\\.\\w+):(\\d+):(\\d+): (ERROR|WARNING)\\: (.*)$",
399
+ "file": 1,
400
+ "line": 3,
401
+ "column": 4,
402
+ "code": 5,
403
+ "message": 6
404
+ },
405
+ "background": {
406
+ "activeOnStart": true,
407
+ "beginsPattern": "^.*VITE v.* ready in \\d* ms.*$",
408
+ "endsPattern": "^.*\\[@tomjs:electron\\] startup electron*$"
409
+ }
410
+ }
411
+ }
412
+ ]
413
+ }
414
+ ```
415
+
416
+ ### Preload process Debug
417
+
418
+ Use `DevTools` to debug the `preload process`.
package/README.zh_CN.md CHANGED
@@ -96,7 +96,7 @@ import { app, BrowserWindow } from 'electron';
96
96
  global.__dirname = dirname(fileURLToPath(import.meta.url));
97
97
 
98
98
  const preload = join(__dirname, '../preload/index.mjs');
99
- const url = process.env.APP_DEV_SERVER_URL;
99
+ const url = process.env.VITE_DEV_SERVER_URL;
100
100
 
101
101
  async function createWindow() {
102
102
  win = new BrowserWindow({
@@ -126,14 +126,12 @@ app.whenReady().then(createWindow);
126
126
 
127
127
  - `package.json`
128
128
 
129
- Electron `preload process` 必须使用 `.mjs` 后缀,否则报错,查看[官方文档](https://www.electronjs.org/zh/docs/latest/tutorial/esm)。所以 `preload` 的 `esm` 默认输出使用 `mjs` 后缀。
130
-
131
- 当 Electron `main process` 的后缀为 `.mjs`或`.cjs` 时, vscode 断点调试无法起到作用,所以后缀默认为`.js`。
129
+ Electron `preload process` 必须使用 `.mjs` 后缀,否则报错,查看[官方文档](https://www.electronjs.org/zh/docs/latest/tutorial/esm)。所以 `preload` 的 `esm` 默认输出使用 `mjs` 后缀。为了保持一致性,`main process` 也以 `.mjs` 结尾。
132
130
 
133
131
  ```json
134
132
  {
135
133
  "type": "module",
136
- "main": "dist/main/index.js"
134
+ "main": "dist/main/index.mjs"
137
135
  }
138
136
  ```
139
137
 
@@ -204,9 +202,9 @@ export default defineConfig({
204
202
  | external | `string[]` | | 不打包这些模块,但是 `dependencies` and `peerDependencies` 默认排除,[详见](https://tsup.egoist.dev/#excluding-packages) |
205
203
  | main | [MainOptions](#MainOptions) | | electron main 进程选项 |
206
204
  | preload | [PreloadOptions](#PreloadOptions) | | electron preload 进程选项 |
207
- | debug | `boolean` | `false` | Electron调试模式,不启动Electron。 您还可以使用 `process.env.APP_ELECTRON_DEBUG` |
208
- | builder | `boolean` | `false` | 如果是`boolean`类型,是否启用[electron-builder](https://www.electron.build)。如果是`Object`,则是[electron-builder](https://www.electron.build)的[配置](https://www.electron.build/configuration/configuration)。 您还可以使用 `process.env.APP_ELECTRON_DEBUG` 开启它。 |
209
- | inspect | `boolean` | `false` | Electron 将监听指定 port 上的 V8 调试协议消息, 外部调试器需要连接到此端口上。您还可以使用 `process.env.APP_ELECTRON_INSPECT`。 有关更多信息,请参阅[debugging-main-process](https://www.electronjs.org/zh/docs/latest/tutorial/debugging-main-process)。 |
205
+ | debug | `boolean` | `false` | Electron调试模式,不启动Electron。 您还可以使用 `process.env.VITE_ELECTRON_DEBUG` |
206
+ | builder | `boolean` | `false` | 如果是`boolean`类型,是否启用[electron-builder](https://www.electron.build)。如果是`Object`,则是[electron-builder](https://www.electron.build)的[配置](https://www.electron.build/configuration/configuration)。 您还可以使用 `process.env.VITE_ELECTRON_DEBUG` 开启它。 |
207
+ | inspect | `boolean` | `false` | Electron 将监听指定 port 上的 V8 调试协议消息, 外部调试器需要连接到此端口上。您还可以使用 `process.env.VITE_ELECTRON_INSPECT`。 有关更多信息,请参阅[debugging-main-process](https://www.electronjs.org/zh/docs/latest/tutorial/debugging-main-process)。 |
210
208
 
211
209
  `recommended` 选项用于设置默认配置和行为,几乎可以达到零配置使用,默认为 `true` 。如果你要自定义配置,请设置它为`false`。以下默认的前提条件是使用推荐的 [项目结构](#目录结构)。
212
210
 
@@ -301,6 +299,24 @@ const config = {
301
299
  | sourcemap | `true` | `false` |
302
300
  | minify | `false` | `true` |
303
301
 
302
+ ## 环境变量
303
+
304
+ ### vite 插件变量
305
+
306
+ | 变量 | 描述 |
307
+ | --- | --- |
308
+ | `VITE_ELECTRON_DEBUG` | Electron主进程调试,不要启动Electron。 当值为 true 或 1 时启用,为 false 或 0 时禁用。默认值未定义。 |
309
+ | `VITE_ELECTRON_INSPECT` | Electron 将在指定端口上侦听 V8 检查器协议消息,外部调试器需要连接到该端口。 当值为 true 时,默认端口为 5858。 |
310
+ | `VITE_ELECTRON_BUILDER` | 启用 [ Electron-builder ](https://www.electron.build) 进行打包。 当值为 true 或 1 时启用,为 false 或 0 时禁用。 默认值未定义。 |
311
+
312
+ ### 应用变量
313
+
314
+ Electron `main process` 和 `renderer process` 使用。
315
+
316
+ | 变量 | 描述 |
317
+ | --------------------- | --------------------- |
318
+ | `VITE_DEV_SERVER_URL` | Vite 开发服务器的 URL |
319
+
304
320
  ## 调试
305
321
 
306
322
  ### Web调试
@@ -329,16 +345,7 @@ app.whenReady().then(() => {
329
345
  });
330
346
  ```
331
347
 
332
- ### 主线程调试
333
-
334
- #### 开启调试
335
-
336
- 通过如下配置或者 `ELECTRON_DEBUG=1 vite dev` 启动代码编译
337
-
338
- - 通过 `.env.development` 文件设置 `APP_ELECTRON_DEBUG=1` 开启
339
- - `vite.config.js` 配置 `electron({ debug: true })` 开启
340
-
341
- #### VSCODE
348
+ ### Main Process 调试
342
349
 
343
350
  通过 `vscode` 运行 `Debug Main Process` 调试主线程,调试工具参考 [官方文档](https://code.visualstudio.com/docs/editor/debugging)
344
351
 
@@ -350,6 +357,7 @@ app.whenReady().then(() => {
350
357
  "configurations": [
351
358
  {
352
359
  "name": "Debug Main Process",
360
+ "preLaunchTask": "npm:debug",
353
361
  "type": "node",
354
362
  "request": "launch",
355
363
  "cwd": "${workspaceFolder}",
@@ -358,8 +366,52 @@ app.whenReady().then(() => {
358
366
  "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd"
359
367
  },
360
368
  "args": ["."],
369
+ "outFiles": [
370
+ "${workspaceFolder}/**/*.js",
371
+ "${workspaceFolder}/**/*.cjs",
372
+ "${workspaceFolder}/**/*.mjs",
373
+ "!**/node_modules/**"
374
+ ],
361
375
  "envFile": "${workspaceFolder}/node_modules/@tomjs/vite-plugin-electron/debug/.env"
362
376
  }
363
377
  ]
364
378
  }
365
379
  ```
380
+
381
+ `tasks.json` 配置如下:
382
+
383
+ ```json
384
+ {
385
+ "version": "2.0.0",
386
+ "tasks": [
387
+ {
388
+ "label": "npm:debug",
389
+ "type": "npm",
390
+ "script": "debug",
391
+ "detail": "cross-env VITE_ELECTRON_DEBUG=1 vite",
392
+ "isBackground": true,
393
+ "problemMatcher": {
394
+ "owner": "typescript",
395
+ "fileLocation": "relative",
396
+ "pattern": {
397
+ "regexp": "^([a-zA-Z]\\:/?([\\w\\-]/?)+\\.\\w+):(\\d+):(\\d+): (ERROR|WARNING)\\: (.*)$",
398
+ "file": 1,
399
+ "line": 3,
400
+ "column": 4,
401
+ "code": 5,
402
+ "message": 6
403
+ },
404
+ "background": {
405
+ "activeOnStart": true,
406
+ "beginsPattern": "^.*VITE v.* ready in \\d* ms.*$",
407
+ "endsPattern": "^.*\\[@tomjs:electron\\] startup electron*$"
408
+ }
409
+ }
410
+ }
411
+ ]
412
+ }
413
+ ```
414
+
415
+ ### Preload Process 调试
416
+
417
+ 使用 `DevTools` 调试 `preload process`.
package/dist/index.d.mts CHANGED
@@ -112,13 +112,13 @@ interface PluginOptions {
112
112
  */
113
113
  builder?: boolean | BuilderOptions;
114
114
  /**
115
- * electron debug mode, don't startup electron. You can also use `process.env.APP_ELECTRON_DEBUG`. Default is false.
115
+ * electron debug mode, don't startup electron. You can also use `process.env.VITE_ELECTRON_DEBUG`. Default is false.
116
116
  * @default false
117
117
  */
118
118
  debug?: boolean;
119
119
  /**
120
120
  * Electron will listen for V8 inspector protocol messages on the specified port, an external debugger will need to connect on this port.
121
- * You can also use `process.env.APP_ELECTRON_INSPECT`. See [debugging-main-process](https://www.electronjs.org/docs/latest/tutorial/debugging-main-process) for more information.
121
+ * You can also use `process.env.VITE_ELECTRON_INSPECT`. See [debugging-main-process](https://www.electronjs.org/docs/latest/tutorial/debugging-main-process) for more information.
122
122
  * The default port is false.
123
123
  * @see https://www.electronjs.org/docs/latest/tutorial/debugging-main-process
124
124
  * @default false
package/dist/index.d.ts CHANGED
@@ -112,13 +112,13 @@ interface PluginOptions {
112
112
  */
113
113
  builder?: boolean | BuilderOptions;
114
114
  /**
115
- * electron debug mode, don't startup electron. You can also use `process.env.APP_ELECTRON_DEBUG`. Default is false.
115
+ * electron debug mode, don't startup electron. You can also use `process.env.VITE_ELECTRON_DEBUG`. Default is false.
116
116
  * @default false
117
117
  */
118
118
  debug?: boolean;
119
119
  /**
120
120
  * Electron will listen for V8 inspector protocol messages on the specified port, an external debugger will need to connect on this port.
121
- * You can also use `process.env.APP_ELECTRON_INSPECT`. See [debugging-main-process](https://www.electronjs.org/docs/latest/tutorial/debugging-main-process) for more information.
121
+ * You can also use `process.env.VITE_ELECTRON_INSPECT`. See [debugging-main-process](https://www.electronjs.org/docs/latest/tutorial/debugging-main-process) for more information.
122
122
  * The default port is false.
123
123
  * @see https://www.electronjs.org/docs/latest/tutorial/debugging-main-process
124
124
  * @default false
package/dist/index.js CHANGED
@@ -1,6 +1,5 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }// src/index.ts
2
2
  var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
3
- var _process = require('process');
4
3
  var _lodashclonedeep = require('lodash.clonedeep'); var _lodashclonedeep2 = _interopRequireDefault(_lodashclonedeep);
5
4
  var _lodashmerge = require('lodash.merge'); var _lodashmerge2 = _interopRequireDefault(_lodashmerge);
6
5
  var _path = require('path'); var _path2 = _interopRequireDefault(_path);
@@ -8,8 +7,9 @@ var _path = require('path'); var _path2 = _interopRequireDefault(_path);
8
7
  // src/builder.ts
9
8
  var _os = require('os'); var _os2 = _interopRequireDefault(_os);
10
9
 
10
+ var _process = require('process');
11
11
 
12
-
12
+ var _shelljs = require('shelljs'); var _shelljs2 = _interopRequireDefault(_shelljs);
13
13
 
14
14
  // src/logger.ts
15
15
  var _dayjs = require('dayjs'); var _dayjs2 = _interopRequireDefault(_dayjs);
@@ -17,7 +17,6 @@ var _kolorist = require('kolorist');
17
17
 
18
18
  // src/constants.ts
19
19
  var PLUGIN_NAME = "@tomjs:electron";
20
- var PACKAGE_NAME = "@tomjs/vite-plugin-electron";
21
20
 
22
21
  // src/logger.ts
23
22
  var Logger = class {
@@ -60,7 +59,6 @@ var createLogger = (tag) => {
60
59
  };
61
60
 
62
61
  // src/utils.ts
63
- var _child_process = require('child_process');
64
62
 
65
63
  var _module = require('module');
66
64
  function readJson(path3) {
@@ -71,8 +69,29 @@ function readJson(path3) {
71
69
  function writeJson(path3, data) {
72
70
  _fs2.default.writeFileSync(path3, JSON.stringify(data, null, 2), "utf8");
73
71
  }
74
- function exec(command, args = [], options) {
75
- return _child_process.spawnSync.call(void 0, command, args, Object.assign({ encoding: "utf8" }, options));
72
+ function resolveHostname(hostname) {
73
+ const loopbackHosts = /* @__PURE__ */ new Set([
74
+ "localhost",
75
+ "127.0.0.1",
76
+ "::1",
77
+ "0000:0000:0000:0000:0000:0000:0000:0001"
78
+ ]);
79
+ const wildcardHosts = /* @__PURE__ */ new Set(["0.0.0.0", "::", "0000:0000:0000:0000:0000:0000:0000:0000"]);
80
+ return loopbackHosts.has(hostname) || wildcardHosts.has(hostname) ? "localhost" : hostname;
81
+ }
82
+ function resolveServerUrl(server) {
83
+ const addressInfo = server.httpServer.address();
84
+ const isAddressInfo = (x) => x == null ? void 0 : x.address;
85
+ if (isAddressInfo(addressInfo)) {
86
+ const { address, port } = addressInfo;
87
+ const hostname = resolveHostname(address);
88
+ const options = server.config.server;
89
+ const protocol = options.https ? "https" : "http";
90
+ const devBase = server.config.base;
91
+ const path3 = typeof options.open === "string" ? options.open : devBase;
92
+ const url = path3.startsWith("http") ? path3 : `${protocol}://${hostname}:${port}${path3}`;
93
+ return url;
94
+ }
76
95
  }
77
96
 
78
97
  // src/builder.ts
@@ -82,8 +101,8 @@ function getMirror() {
82
101
  if (mirror) {
83
102
  return mirror;
84
103
  }
85
- const res = exec(_os2.default.platform() === "win32" ? "npm.cmd" : "npm", ["config", "get", "registry"]);
86
- if (res.status === 0) {
104
+ const res = _shelljs2.default.exec("npm config get registry", { silent: true });
105
+ if (res.code === 0) {
87
106
  let registry = res.stdout;
88
107
  if (!registry) {
89
108
  return;
@@ -214,7 +233,7 @@ async function runElectronBuilder(options, resolvedConfig) {
214
233
  logger.info("building electron app...");
215
234
  const DIST_PATH = _path2.default.join(_process.cwd.call(void 0, ), _path2.default.dirname(resolvedConfig.build.outDir));
216
235
  logger.info(`create package.json and exec "npm install"`);
217
- exec(`cd ${DIST_PATH} && npm run build`);
236
+ _shelljs2.default.exec(`cd ${DIST_PATH} && npm i`);
218
237
  logger.info(`run electron-builder to package app`);
219
238
  const config = getBuilderConfig(options, resolvedConfig);
220
239
  const { build } = await Promise.resolve().then(() => _interopRequireWildcard(require("electron-builder")));
@@ -224,7 +243,7 @@ async function runElectronBuilder(options, resolvedConfig) {
224
243
  }
225
244
 
226
245
  // src/main.ts
227
-
246
+ var _child_process = require('child_process');
228
247
  var _electron = require('electron'); var _electron2 = _interopRequireDefault(_electron);
229
248
  var _treekill = require('tree-kill'); var _treekill2 = _interopRequireDefault(_treekill);
230
249
  var _tsup = require('tsup');
@@ -292,19 +311,19 @@ async function runServe(options, server) {
292
311
  }
293
312
  if (buildCounts[i] <= 0) {
294
313
  buildCounts[i]++;
295
- logger2.info(`${name} build succeeded`);
314
+ logger2.info(`${name} build success`);
296
315
  if (buildCounts[0] == 1 && buildCounts[1] == 1) {
297
- logger2.info("electron startup");
316
+ logger2.info("startup electron");
298
317
  await startup(options);
299
318
  }
300
319
  return;
301
320
  }
302
- logger2.success(`${name} rebuild succeeded!`);
321
+ logger2.success(`${name} rebuild success`);
303
322
  if (name === "main") {
304
- logger2.info("electron restart");
323
+ logger2.info("restart electron");
305
324
  await startup(options);
306
325
  } else {
307
- logger2.info("page reload");
326
+ logger2.info("reload page");
308
327
  server.ws.send({
309
328
  type: "full-reload"
310
329
  });
@@ -341,7 +360,12 @@ function preMergeOptions(options) {
341
360
  format,
342
361
  clean: true,
343
362
  dts: false,
344
- treeshake: !!isDev
363
+ treeshake: !!isDev,
364
+ outExtension({ format: format2 }) {
365
+ return {
366
+ js: format2 === "esm" ? ".mjs" : `.js`
367
+ };
368
+ }
345
369
  };
346
370
  const opts = _lodashmerge2.default.call(void 0,
347
371
  {
@@ -352,12 +376,7 @@ function preMergeOptions(options) {
352
376
  ...electron2
353
377
  },
354
378
  preload: {
355
- ...electron2,
356
- outExtension({ format: format2 }) {
357
- return {
358
- js: format2 === "esm" ? ".mjs" : `.js`
359
- };
360
- }
379
+ ...electron2
361
380
  },
362
381
  builder: false
363
382
  },
@@ -382,7 +401,7 @@ function preMergeOptions(options) {
382
401
  return opts;
383
402
  }
384
403
  function geNumberBooleanValue(value) {
385
- if (typeof value !== "string") {
404
+ if (typeof value !== "string" || value.trim() === "") {
386
405
  return;
387
406
  }
388
407
  if (["true", "false"].includes(value)) {
@@ -391,6 +410,18 @@ function geNumberBooleanValue(value) {
391
410
  const v = Number(value);
392
411
  return Number.isNaN(v) ? void 0 : v;
393
412
  }
413
+ function getBooleanValue(value) {
414
+ if (typeof value !== "string" || value.trim() === "") {
415
+ return;
416
+ }
417
+ if (["true", "false"].includes(value)) {
418
+ return value === "true";
419
+ }
420
+ if (["1", "0"].includes(value)) {
421
+ return value === "1";
422
+ }
423
+ return;
424
+ }
394
425
  function useElectronPlugin(options) {
395
426
  const opts = preMergeOptions(options);
396
427
  let isServer = false;
@@ -418,25 +449,16 @@ function useElectronPlugin(options) {
418
449
  opts.main.minify ??= true;
419
450
  opts.preload.minify ??= true;
420
451
  }
421
- let envPrefix = config.envPrefix;
422
- if (!envPrefix) {
423
- envPrefix = ["VITE_"];
424
- } else if (typeof envPrefix === "string") {
425
- envPrefix = [envPrefix];
426
- }
427
- if (!envPrefix.includes("APP_")) {
428
- envPrefix.push("APP_");
429
- }
430
452
  return {
431
- envPrefix: [...new Set(envPrefix)],
432
453
  build: {
433
454
  outDir
434
455
  }
435
456
  };
436
457
  },
437
458
  configResolved(config) {
438
- opts.debug = config.env.APP_ELECTRON_DEBUG ? !!config.env.APP_ELECTRON_DEBUG : opts.debug;
439
- opts.inspect = config.env.APP_ELECTRON_INSPECT ? geNumberBooleanValue(config.env.APP_ELECTRON_INSPECT) : opts.inspect;
459
+ opts.debug = _nullishCoalesce(getBooleanValue(config.env.VITE_ELECTRON_DEBUG), () => ( opts.debug));
460
+ opts.inspect = _nullishCoalesce(geNumberBooleanValue(config.env.VITE_ELECTRON_INSPECT), () => ( opts.inspect));
461
+ opts.builder = _nullishCoalesce(getBooleanValue(config.env.VITE_ELECTRON_BUILDER), () => ( opts.builder));
440
462
  resolvedConfig = config;
441
463
  },
442
464
  configureServer(server) {
@@ -444,19 +466,13 @@ function useElectronPlugin(options) {
444
466
  return;
445
467
  }
446
468
  server.httpServer.on("listening", async () => {
447
- var _a;
448
- const serve = (_a = server.httpServer) == null ? void 0 : _a.address();
449
- const { address, port, family } = serve;
450
- const hostname = family === "IPv6" ? `[${address}]` : address;
451
- const protocol = server.config.server.https ? "https" : "http";
452
- process.env.APP_DEV_SERVER_URL = `${protocol}://${hostname}:${port}`;
453
- const DEBUG_PATH = _path2.default.resolve(_process.cwd.call(void 0, ), "node_modules", PACKAGE_NAME, "debug");
454
- if (!_fs2.default.existsSync(DEBUG_PATH)) {
455
- _fs.mkdirSync.call(void 0, DEBUG_PATH, { recursive: true });
456
- }
457
- const env = Object.keys(process.env).filter((s) => s.startsWith("APP_") || s.startsWith("VITE_")).map((s) => `${s}=${process.env[s]}`).join("\n");
458
- _fs.writeFileSync.call(void 0, _path2.default.join(DEBUG_PATH, ".env"), `NODE_ENV=development
459
- ${env}`);
469
+ const env = {
470
+ NODE_ENV: server.config.mode || "development",
471
+ VITE_DEV_SERVER_URL: resolveServerUrl(server)
472
+ };
473
+ ["main", "preload"].forEach((prop) => {
474
+ opts[prop].env = env;
475
+ });
460
476
  await runServe(opts, server);
461
477
  });
462
478
  },
package/dist/index.mjs CHANGED
@@ -1,6 +1,5 @@
1
1
  // src/index.ts
2
- import fs2, { mkdirSync, writeFileSync } from "fs";
3
- import { cwd as cwd2 } from "process";
2
+ import fs2 from "fs";
4
3
  import cloneDeep from "lodash.clonedeep";
5
4
  import merge2 from "lodash.merge";
6
5
  import path2 from "path";
@@ -10,6 +9,7 @@ import os from "os";
10
9
  import path from "path";
11
10
  import { cwd } from "process";
12
11
  import merge from "lodash.merge";
12
+ import shell from "shelljs";
13
13
 
14
14
  // src/logger.ts
15
15
  import dayjs from "dayjs";
@@ -17,7 +17,6 @@ import { blue, gray, green, red, yellow } from "kolorist";
17
17
 
18
18
  // src/constants.ts
19
19
  var PLUGIN_NAME = "@tomjs:electron";
20
- var PACKAGE_NAME = "@tomjs/vite-plugin-electron";
21
20
 
22
21
  // src/logger.ts
23
22
  var Logger = class {
@@ -60,7 +59,6 @@ var createLogger = (tag) => {
60
59
  };
61
60
 
62
61
  // src/utils.ts
63
- import { spawnSync } from "child_process";
64
62
  import fs from "fs";
65
63
  function readJson(path3) {
66
64
  if (fs.existsSync(path3)) {
@@ -70,8 +68,29 @@ function readJson(path3) {
70
68
  function writeJson(path3, data) {
71
69
  fs.writeFileSync(path3, JSON.stringify(data, null, 2), "utf8");
72
70
  }
73
- function exec(command, args = [], options) {
74
- return spawnSync(command, args, Object.assign({ encoding: "utf8" }, options));
71
+ function resolveHostname(hostname) {
72
+ const loopbackHosts = /* @__PURE__ */ new Set([
73
+ "localhost",
74
+ "127.0.0.1",
75
+ "::1",
76
+ "0000:0000:0000:0000:0000:0000:0000:0001"
77
+ ]);
78
+ const wildcardHosts = /* @__PURE__ */ new Set(["0.0.0.0", "::", "0000:0000:0000:0000:0000:0000:0000:0000"]);
79
+ return loopbackHosts.has(hostname) || wildcardHosts.has(hostname) ? "localhost" : hostname;
80
+ }
81
+ function resolveServerUrl(server) {
82
+ const addressInfo = server.httpServer.address();
83
+ const isAddressInfo = (x) => x == null ? void 0 : x.address;
84
+ if (isAddressInfo(addressInfo)) {
85
+ const { address, port } = addressInfo;
86
+ const hostname = resolveHostname(address);
87
+ const options = server.config.server;
88
+ const protocol = options.https ? "https" : "http";
89
+ const devBase = server.config.base;
90
+ const path3 = typeof options.open === "string" ? options.open : devBase;
91
+ const url = path3.startsWith("http") ? path3 : `${protocol}://${hostname}:${port}${path3}`;
92
+ return url;
93
+ }
75
94
  }
76
95
 
77
96
  // src/builder.ts
@@ -81,8 +100,8 @@ function getMirror() {
81
100
  if (mirror) {
82
101
  return mirror;
83
102
  }
84
- const res = exec(os.platform() === "win32" ? "npm.cmd" : "npm", ["config", "get", "registry"]);
85
- if (res.status === 0) {
103
+ const res = shell.exec("npm config get registry", { silent: true });
104
+ if (res.code === 0) {
86
105
  let registry = res.stdout;
87
106
  if (!registry) {
88
107
  return;
@@ -213,7 +232,7 @@ async function runElectronBuilder(options, resolvedConfig) {
213
232
  logger.info("building electron app...");
214
233
  const DIST_PATH = path.join(cwd(), path.dirname(resolvedConfig.build.outDir));
215
234
  logger.info(`create package.json and exec "npm install"`);
216
- exec(`cd ${DIST_PATH} && npm run build`);
235
+ shell.exec(`cd ${DIST_PATH} && npm i`);
217
236
  logger.info(`run electron-builder to package app`);
218
237
  const config = getBuilderConfig(options, resolvedConfig);
219
238
  const { build } = await import("electron-builder");
@@ -291,19 +310,19 @@ async function runServe(options, server) {
291
310
  }
292
311
  if (buildCounts[i] <= 0) {
293
312
  buildCounts[i]++;
294
- logger2.info(`${name} build succeeded`);
313
+ logger2.info(`${name} build success`);
295
314
  if (buildCounts[0] == 1 && buildCounts[1] == 1) {
296
- logger2.info("electron startup");
315
+ logger2.info("startup electron");
297
316
  await startup(options);
298
317
  }
299
318
  return;
300
319
  }
301
- logger2.success(`${name} rebuild succeeded!`);
320
+ logger2.success(`${name} rebuild success`);
302
321
  if (name === "main") {
303
- logger2.info("electron restart");
322
+ logger2.info("restart electron");
304
323
  await startup(options);
305
324
  } else {
306
- logger2.info("page reload");
325
+ logger2.info("reload page");
307
326
  server.ws.send({
308
327
  type: "full-reload"
309
328
  });
@@ -340,7 +359,12 @@ function preMergeOptions(options) {
340
359
  format,
341
360
  clean: true,
342
361
  dts: false,
343
- treeshake: !!isDev
362
+ treeshake: !!isDev,
363
+ outExtension({ format: format2 }) {
364
+ return {
365
+ js: format2 === "esm" ? ".mjs" : `.js`
366
+ };
367
+ }
344
368
  };
345
369
  const opts = merge2(
346
370
  {
@@ -351,12 +375,7 @@ function preMergeOptions(options) {
351
375
  ...electron2
352
376
  },
353
377
  preload: {
354
- ...electron2,
355
- outExtension({ format: format2 }) {
356
- return {
357
- js: format2 === "esm" ? ".mjs" : `.js`
358
- };
359
- }
378
+ ...electron2
360
379
  },
361
380
  builder: false
362
381
  },
@@ -381,7 +400,7 @@ function preMergeOptions(options) {
381
400
  return opts;
382
401
  }
383
402
  function geNumberBooleanValue(value) {
384
- if (typeof value !== "string") {
403
+ if (typeof value !== "string" || value.trim() === "") {
385
404
  return;
386
405
  }
387
406
  if (["true", "false"].includes(value)) {
@@ -390,6 +409,18 @@ function geNumberBooleanValue(value) {
390
409
  const v = Number(value);
391
410
  return Number.isNaN(v) ? void 0 : v;
392
411
  }
412
+ function getBooleanValue(value) {
413
+ if (typeof value !== "string" || value.trim() === "") {
414
+ return;
415
+ }
416
+ if (["true", "false"].includes(value)) {
417
+ return value === "true";
418
+ }
419
+ if (["1", "0"].includes(value)) {
420
+ return value === "1";
421
+ }
422
+ return;
423
+ }
393
424
  function useElectronPlugin(options) {
394
425
  const opts = preMergeOptions(options);
395
426
  let isServer = false;
@@ -417,25 +448,16 @@ function useElectronPlugin(options) {
417
448
  opts.main.minify ??= true;
418
449
  opts.preload.minify ??= true;
419
450
  }
420
- let envPrefix = config.envPrefix;
421
- if (!envPrefix) {
422
- envPrefix = ["VITE_"];
423
- } else if (typeof envPrefix === "string") {
424
- envPrefix = [envPrefix];
425
- }
426
- if (!envPrefix.includes("APP_")) {
427
- envPrefix.push("APP_");
428
- }
429
451
  return {
430
- envPrefix: [...new Set(envPrefix)],
431
452
  build: {
432
453
  outDir
433
454
  }
434
455
  };
435
456
  },
436
457
  configResolved(config) {
437
- opts.debug = config.env.APP_ELECTRON_DEBUG ? !!config.env.APP_ELECTRON_DEBUG : opts.debug;
438
- opts.inspect = config.env.APP_ELECTRON_INSPECT ? geNumberBooleanValue(config.env.APP_ELECTRON_INSPECT) : opts.inspect;
458
+ opts.debug = getBooleanValue(config.env.VITE_ELECTRON_DEBUG) ?? opts.debug;
459
+ opts.inspect = geNumberBooleanValue(config.env.VITE_ELECTRON_INSPECT) ?? opts.inspect;
460
+ opts.builder = getBooleanValue(config.env.VITE_ELECTRON_BUILDER) ?? opts.builder;
439
461
  resolvedConfig = config;
440
462
  },
441
463
  configureServer(server) {
@@ -443,19 +465,13 @@ function useElectronPlugin(options) {
443
465
  return;
444
466
  }
445
467
  server.httpServer.on("listening", async () => {
446
- var _a;
447
- const serve = (_a = server.httpServer) == null ? void 0 : _a.address();
448
- const { address, port, family } = serve;
449
- const hostname = family === "IPv6" ? `[${address}]` : address;
450
- const protocol = server.config.server.https ? "https" : "http";
451
- process.env.APP_DEV_SERVER_URL = `${protocol}://${hostname}:${port}`;
452
- const DEBUG_PATH = path2.resolve(cwd2(), "node_modules", PACKAGE_NAME, "debug");
453
- if (!fs2.existsSync(DEBUG_PATH)) {
454
- mkdirSync(DEBUG_PATH, { recursive: true });
455
- }
456
- const env = Object.keys(process.env).filter((s) => s.startsWith("APP_") || s.startsWith("VITE_")).map((s) => `${s}=${process.env[s]}`).join("\n");
457
- writeFileSync(path2.join(DEBUG_PATH, ".env"), `NODE_ENV=development
458
- ${env}`);
468
+ const env = {
469
+ NODE_ENV: server.config.mode || "development",
470
+ VITE_DEV_SERVER_URL: resolveServerUrl(server)
471
+ };
472
+ ["main", "preload"].forEach((prop) => {
473
+ opts[prop].env = env;
474
+ });
459
475
  await runServe(opts, server);
460
476
  });
461
477
  },
package/env.d.ts CHANGED
@@ -12,14 +12,6 @@ declare namespace NodeJS {
12
12
  /**
13
13
  * The url of the dev server.
14
14
  */
15
- APP_DEV_SERVER_URL?: string;
16
- /**
17
- * Electron main process debug, don't startup electron
18
- */
19
- APP_ELECTRON_DEBUG?: string;
20
- /**
21
- * Electron will listen for V8 inspector protocol messages on the specified port, an external debugger will need to connect on this port. The default port is 5858.
22
- */
23
- APP_ELECTRON_INSPECT?: string;
15
+ VITE_DEV_SERVER_URL?: string;
24
16
  }
25
17
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomjs/vite-plugin-electron",
3
- "version": "1.5.0",
3
+ "version": "1.7.0",
4
4
  "description": "A simple vite plugin for electron, supports esm/cjs, support esm in electron v28+",
5
5
  "keywords": [
6
6
  "vite",
@@ -40,21 +40,12 @@
40
40
  "type": "git",
41
41
  "url": "git+https://github.com/tomgao365/vite-plugin-electron.git"
42
42
  },
43
- "scripts": {
44
- "dev": "tsup --watch",
45
- "build": "tsup",
46
- "lint": "run-s lint:eslint lint:stylelint lint:prettier",
47
- "lint:eslint": "eslint \"{src,examples}/**/*.{js,cjs,ts,tsx,vue}\" *.{js,cjs,ts} --fix --cache",
48
- "lint:stylelint": "stylelint \"examples/**/*.{css,scss,less,vue,html}\" --fix --cache",
49
- "lint:prettier": "prettier --write .",
50
- "prepare": "husky install",
51
- "prepublishOnly": "npm run build && np --any-branch --no-yarn --yolo --no-publish --message \"chore: release v%s\""
52
- },
53
43
  "dependencies": {
54
44
  "dayjs": "^1.11.10",
55
45
  "kolorist": "^1.8.0",
56
46
  "lodash.clonedeep": "^4.5.0",
57
47
  "lodash.merge": "^4.6.2",
48
+ "shelljs": "^0.8.5",
58
49
  "tree-kill": "^1.2.2",
59
50
  "tsup": "7.2.0"
60
51
  },
@@ -68,6 +59,7 @@
68
59
  "@types/lodash.clonedeep": "^4.5.9",
69
60
  "@types/lodash.merge": "^4.6.9",
70
61
  "@types/node": "^18.19.3",
62
+ "@types/shelljs": "^0.8.15",
71
63
  "eslint": "^8.55.0",
72
64
  "husky": "^8.0.3",
73
65
  "lint-staged": "^15.2.0",
@@ -88,5 +80,13 @@
88
80
  "electron-builder": {
89
81
  "optional": true
90
82
  }
83
+ },
84
+ "scripts": {
85
+ "dev": "tsup --watch",
86
+ "build": "tsup",
87
+ "lint": "run-s lint:eslint lint:stylelint lint:prettier",
88
+ "lint:eslint": "eslint \"{src,examples}/**/*.{js,cjs,ts,tsx,vue}\" *.{js,cjs,ts} --fix --cache",
89
+ "lint:stylelint": "stylelint \"examples/**/*.{css,scss,less,vue,html}\" --fix --cache",
90
+ "lint:prettier": "prettier --write ."
91
91
  }
92
- }
92
+ }