@tomjs/vite-plugin-electron 1.3.8 → 1.3.9-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
@@ -16,6 +16,7 @@ Many thanks to [caoxiemeihao](https://github.com/caoxiemeihao)'s [vite-plugin-el
16
16
  - Support `preload`'s `Hot Reload`
17
17
  - Support `esm` and `cjs`, you can use `esm` in [electron v28+](https://www.electronjs.org/blog/electron-28-0)
18
18
  - Support `vue` and `react` and other [frameworks](https://vitejs.dev/guide/#trying-vite-online) supported by `vite`
19
+ - Optional [electron-builder](https://www.electron.build/) Simple configuration
19
20
 
20
21
  ## Install
21
22
 
@@ -218,6 +219,63 @@ Based on [Options](https://paka.dev/npm/tsup) of [tsup](https://tsup.egoist.dev/
218
219
  | outDir | `string` | "dist-electron/preload" | The output directory for the preload process files |
219
220
  | onSuccess | `() => Promise<void \| undefined \| (() => void \| Promise<void>)>` | `undefined` | A function that will be executed after the build succeeds. |
220
221
 
222
+ # BuilderOptions
223
+
224
+ When `recommended` and `builder.enable` are both `true`, use [electron-builder](https://www.electron.build) to package Electron applications.
225
+
226
+ - In the `build.outDir` directory configured in vite, generate a new package.json based on the configuration and package.json, excluding non-dependencies.
227
+ - Execute `npm install` and then package.
228
+
229
+ _Not suitable for everyone._
230
+
231
+ To use this function, you need to install additional `electron-builder`
232
+
233
+ | Property | Type | Default | Description |
234
+ | --- | --- | --- | --- |
235
+ | enable | `boolean` | `false` | Whether to enable the [electron-builder](https://www.electron.build). |
236
+ | appId | `string` | `"com.electron.${name}"` | The application id. [See More](https://www.electron.build/configuration/configuration#configuration) |
237
+ | productName | `string` | `"com.electron.${name}"` | product name.[See More](https://www.electron.build/configuration/configuration#configuration) |
238
+ | builderConfig | [Configuration](https://www.electron.build/configuration/configuration#configurationF) | `undefined` | [electron-builder](https://www.electron.build)'s [Configuration](https://www.electron.build/configuration/configuration#configuration) |
239
+
240
+ The default configuration is as follows:
241
+
242
+ ```ts
243
+ const config = {
244
+ directories: {
245
+ buildResources: 'electron/build',
246
+ app: path.dirname(resolvedConfig.build.outDir),
247
+ output: 'release/${version}',
248
+ },
249
+ files: ['main', 'preload', 'renderer'],
250
+ artifactName: '${productName}-${version}-${os}-${arch}.${ext}',
251
+ electronDownload: {
252
+ // when npm registry mirror is 'registry.npmmirror.com'
253
+ mirror: 'https://npmmirror.com/mirrors/electron',
254
+ },
255
+ electronLanguages: ['zh-CN', 'en-US'],
256
+ win: {
257
+ target: [
258
+ {
259
+ target: 'nsis',
260
+ arch: ['x64'],
261
+ },
262
+ ],
263
+ },
264
+ mac: {
265
+ target: ['dmg'],
266
+ },
267
+ linux: {
268
+ target: ['zip'],
269
+ },
270
+ nsis: {
271
+ oneClick: false,
272
+ perMachine: false,
273
+ allowToChangeInstallationDirectory: true,
274
+ deleteAppDataOnUninstall: false,
275
+ },
276
+ };
277
+ ```
278
+
221
279
  ### Additional Information
222
280
 
223
281
  - Default values for `main` and `preload` when the relevant parameters are not configured
package/README.zh_CN.md CHANGED
@@ -16,6 +16,7 @@
16
16
  - 支持 `preload` 的 `热重载`
17
17
  - 支持 `esm` 和 `cjs` ,你可以在 [electron v28+](https://www.electronjs.org/zh/blog/electron-28-0) 中使用 `esm`
18
18
  - 支持 `vue` 和 `react` 等其他 `vite` 支持的[框架](https://cn.vitejs.dev/guide/#trying-vite-online)
19
+ - 可选 [electron-builder](https://www.electron.build/) 简单配置打包
19
20
 
20
21
  ## 安装
21
22
 
@@ -217,6 +218,63 @@ export default defineConfig({
217
218
  | outDir | `string` | `"dist-electron/preload"` | preload 输出文件夹 |
218
219
  | onSuccess | `() => Promise<void \| undefined \| (() => void \| Promise<void>)>` | `undefined` | 构建成功后运行的回调函数 |
219
220
 
221
+ ### BuilderOptions
222
+
223
+ 当 `recommended` 和 `builder.enable` 都为 `true` 时,使用 [electron-builder](https://www.electron.build) 打包 Electron 应用程序。
224
+
225
+ - 在vite中配置的`build.outDir`目录中,根据配置和package.json生成新的package.json,排除非依赖项。
226
+ - 执行`npm install`然后打包。
227
+
228
+ _不适合所有人使用。_
229
+
230
+ 使用该功能,需要额外安装 `electron-builder`
231
+
232
+ | 参数名 | 类型 | 默认值 | 说明 |
233
+ | --- | --- | --- | --- |
234
+ | enable | `boolean` | `false` | 是否启用 [electron-builder](https://www.electron.build) |
235
+ | appId | `string` | `"com.electron.${name}"` | 应用程序 ID。[详细](https://www.electron.build/configuration/configuration#configuration) |
236
+ | productName | `string` | `` | 应用程序名称。[详细](https://www.electron.build/configuration/configuration#configuration) |
237
+ | builderConfig | [Configuration](https://www.electron.build/configuration/configuration#configurationF) | `undefined` | [electron-builder](https://www.electron.build) 的 [Configuration](https://www.electron.build/configuration/configuration#configuration) |
238
+
239
+ 默认配置如下
240
+
241
+ ```ts
242
+ const config = {
243
+ directories: {
244
+ buildResources: 'electron/build',
245
+ app: path.dirname(resolvedConfig.build.outDir),
246
+ output: 'release/${version}',
247
+ },
248
+ files: ['main', 'preload', 'renderer'],
249
+ artifactName: '${productName}-${version}-${os}-${arch}.${ext}',
250
+ electronDownload: {
251
+ // when npm registry mirror is 'registry.npmmirror.com'
252
+ mirror: 'https://npmmirror.com/mirrors/electron',
253
+ },
254
+ electronLanguages: ['zh-CN', 'en-US'],
255
+ win: {
256
+ target: [
257
+ {
258
+ target: 'nsis',
259
+ arch: ['x64'],
260
+ },
261
+ ],
262
+ },
263
+ mac: {
264
+ target: ['dmg'],
265
+ },
266
+ linux: {
267
+ target: ['zip'],
268
+ },
269
+ nsis: {
270
+ oneClick: false,
271
+ perMachine: false,
272
+ allowToChangeInstallationDirectory: true,
273
+ deleteAppDataOnUninstall: false,
274
+ },
275
+ };
276
+ ```
277
+
220
278
  ### 补充说明
221
279
 
222
280
  - `main` 和 `preload` 未配置相关参数时的默认值
package/dist/index.d.mts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { Plugin } from 'vite';
2
+ import { Configuration } from 'electron-builder';
2
3
  import { Options } from 'tsup';
3
4
 
4
5
  /**
@@ -49,6 +50,34 @@ interface PreloadOptions extends Omit<Options, 'entry' | 'format' | 'outDir' | '
49
50
  */
50
51
  onSuccess?: () => Promise<void | undefined | (() => void | Promise<void>)>;
51
52
  }
53
+ /**
54
+ * When `recommended` and `builder.enable` are both `true`, use [electron-builder](https://www.electron.build) to package Electron applications.
55
+ *
56
+ * * In the `build.outDir` directory configured in vite, generate a new package.json based on the configuration and package.json, excluding non-dependencies.
57
+ * * Execute `npm install` and then package.
58
+ */
59
+ interface BuilderOptions {
60
+ /**
61
+ * Whether to enable the [electron-builder](https://www.electron.build), the default is false.
62
+ * @default false
63
+ */
64
+ enable?: boolean;
65
+ /**
66
+ * The application id. Used as [CFBundleIdentifier](https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/20001431-102070) for MacOS and as
67
+ * [Application User Model ID](https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx) for Windows (NSIS target only, Squirrel.Windows not supported). It is strongly recommended that an explicit ID is set.
68
+ * @default com.electron.${name}
69
+ */
70
+ appId?: string | null;
71
+ /**
72
+ * As [name](#Metadata-name), but allows you to specify a product name for your executable which contains spaces and other special characters not allowed in the [name property](https://docs.npmjs.com/files/package.json#name).
73
+ * If not specified inside of the `build` configuration, `productName` property defined at the top level of `package.json` is used. If not specified at the top level of `package.json`, [name property](https://docs.npmjs.com/files/package.json#name) is used.
74
+ */
75
+ productName?: string | null;
76
+ /**
77
+ * The [electron-builder](https://www.electron.build/configuration/configuration) configuration.
78
+ */
79
+ builderConfig?: Configuration;
80
+ }
52
81
  /**
53
82
  * vite plugin options
54
83
  */
@@ -65,7 +94,7 @@ interface PluginOptions {
65
94
  * Don't bundle these modules, but dependencies and peerDependencies in your package.json are always excluded. [See more](https://tsup.egoist.dev/#excluding-packages)
66
95
  * @see https://tsup.egoist.dev/#excluding-packages
67
96
  */
68
- external?: string[];
97
+ external?: (string | RegExp)[];
69
98
  /**
70
99
  * electron main process options
71
100
  */
@@ -74,6 +103,13 @@ interface PluginOptions {
74
103
  * electron preload process options
75
104
  */
76
105
  preload?: PreloadOptions;
106
+ /**
107
+ * When `recommended` and `builder.enable` are both `true`, use [electron-builder](https://www.electron.build) to package Electron applications.
108
+ *
109
+ * * In the `build.outDir` directory configured in vite, generate a new package.json based on the configuration and package.json, excluding non-dependencies.
110
+ * * Execute `npm install` and then package.
111
+ */
112
+ builder?: BuilderOptions;
77
113
  /**
78
114
  * electron debug mode, don't startup electron. You can also use `process.env.APP_ELECTRON_DEBUG`. Default is false.
79
115
  * @default false
@@ -89,6 +125,10 @@ interface PluginOptions {
89
125
  inspect?: number | boolean;
90
126
  }
91
127
 
92
- declare function vitePluginElectron(options?: PluginOptions): Plugin;
128
+ /**
129
+ * A simple vite plugin for electron
130
+ * @param options
131
+ */
132
+ declare function useElectronPlugin(options?: PluginOptions): Plugin;
93
133
 
94
- export { MainOptions, PluginOptions, PreloadOptions, vitePluginElectron as default, vitePluginElectron };
134
+ export { BuilderOptions, MainOptions, PluginOptions, PreloadOptions, useElectronPlugin as default, useElectronPlugin };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { Plugin } from 'vite';
2
+ import { Configuration } from 'electron-builder';
2
3
  import { Options } from 'tsup';
3
4
 
4
5
  /**
@@ -49,6 +50,34 @@ interface PreloadOptions extends Omit<Options, 'entry' | 'format' | 'outDir' | '
49
50
  */
50
51
  onSuccess?: () => Promise<void | undefined | (() => void | Promise<void>)>;
51
52
  }
53
+ /**
54
+ * When `recommended` and `builder.enable` are both `true`, use [electron-builder](https://www.electron.build) to package Electron applications.
55
+ *
56
+ * * In the `build.outDir` directory configured in vite, generate a new package.json based on the configuration and package.json, excluding non-dependencies.
57
+ * * Execute `npm install` and then package.
58
+ */
59
+ interface BuilderOptions {
60
+ /**
61
+ * Whether to enable the [electron-builder](https://www.electron.build), the default is false.
62
+ * @default false
63
+ */
64
+ enable?: boolean;
65
+ /**
66
+ * The application id. Used as [CFBundleIdentifier](https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/20001431-102070) for MacOS and as
67
+ * [Application User Model ID](https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx) for Windows (NSIS target only, Squirrel.Windows not supported). It is strongly recommended that an explicit ID is set.
68
+ * @default com.electron.${name}
69
+ */
70
+ appId?: string | null;
71
+ /**
72
+ * As [name](#Metadata-name), but allows you to specify a product name for your executable which contains spaces and other special characters not allowed in the [name property](https://docs.npmjs.com/files/package.json#name).
73
+ * If not specified inside of the `build` configuration, `productName` property defined at the top level of `package.json` is used. If not specified at the top level of `package.json`, [name property](https://docs.npmjs.com/files/package.json#name) is used.
74
+ */
75
+ productName?: string | null;
76
+ /**
77
+ * The [electron-builder](https://www.electron.build/configuration/configuration) configuration.
78
+ */
79
+ builderConfig?: Configuration;
80
+ }
52
81
  /**
53
82
  * vite plugin options
54
83
  */
@@ -65,7 +94,7 @@ interface PluginOptions {
65
94
  * Don't bundle these modules, but dependencies and peerDependencies in your package.json are always excluded. [See more](https://tsup.egoist.dev/#excluding-packages)
66
95
  * @see https://tsup.egoist.dev/#excluding-packages
67
96
  */
68
- external?: string[];
97
+ external?: (string | RegExp)[];
69
98
  /**
70
99
  * electron main process options
71
100
  */
@@ -74,6 +103,13 @@ interface PluginOptions {
74
103
  * electron preload process options
75
104
  */
76
105
  preload?: PreloadOptions;
106
+ /**
107
+ * When `recommended` and `builder.enable` are both `true`, use [electron-builder](https://www.electron.build) to package Electron applications.
108
+ *
109
+ * * In the `build.outDir` directory configured in vite, generate a new package.json based on the configuration and package.json, excluding non-dependencies.
110
+ * * Execute `npm install` and then package.
111
+ */
112
+ builder?: BuilderOptions;
77
113
  /**
78
114
  * electron debug mode, don't startup electron. You can also use `process.env.APP_ELECTRON_DEBUG`. Default is false.
79
115
  * @default false
@@ -89,6 +125,10 @@ interface PluginOptions {
89
125
  inspect?: number | boolean;
90
126
  }
91
127
 
92
- declare function vitePluginElectron(options?: PluginOptions): Plugin;
128
+ /**
129
+ * A simple vite plugin for electron
130
+ * @param options
131
+ */
132
+ declare function useElectronPlugin(options?: PluginOptions): Plugin;
93
133
 
94
- export { MainOptions, PluginOptions, PreloadOptions, vitePluginElectron as default, vitePluginElectron };
134
+ export { BuilderOptions, MainOptions, PluginOptions, PreloadOptions, useElectronPlugin as default, useElectronPlugin };
package/dist/index.js CHANGED
@@ -1,15 +1,167 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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
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
3
  var _process = require('process');
4
4
  var _lodashclonedeep = require('lodash.clonedeep'); var _lodashclonedeep2 = _interopRequireDefault(_lodashclonedeep);
5
5
  var _lodashmerge = require('lodash.merge'); var _lodashmerge2 = _interopRequireDefault(_lodashmerge);
6
6
  var _path = require('path'); var _path2 = _interopRequireDefault(_path);
7
7
 
8
+ // src/builder.ts
9
+ var _os = require('os'); var _os2 = _interopRequireDefault(_os);
10
+
11
+
12
+
13
+ var _shelljs = require('shelljs'); var _shelljs2 = _interopRequireDefault(_shelljs);
14
+
15
+ // src/utils.ts
16
+ var _child_process = require('child_process');
17
+
18
+ var _module = require('module');
19
+ function readJson(path3) {
20
+ if (_fs2.default.existsSync(path3)) {
21
+ return JSON.parse(_fs2.default.readFileSync(path3, "utf8"));
22
+ }
23
+ }
24
+ function writeJson(path3, data) {
25
+ _fs2.default.writeFileSync(path3, JSON.stringify(data, null, 2), "utf8");
26
+ }
27
+ function exec(command, args, options) {
28
+ return _child_process.spawnSync.call(void 0, command, args, Object.assign({ encoding: "utf8" }, options));
29
+ }
30
+
31
+ // src/builder.ts
32
+ function getMirror() {
33
+ let mirror = process.env.ELECTRON_MIRROR;
34
+ if (mirror) {
35
+ return mirror;
36
+ }
37
+ const res = exec(_os2.default.platform() === "win32" ? "npm.cmd" : "npm", ["config", "get", "registry"]);
38
+ if (res.status === 0) {
39
+ let registry = res.stdout;
40
+ if (!registry) {
41
+ return;
42
+ }
43
+ registry = registry.trim();
44
+ if (registry && ["registry.npmmirror.com", "registry.npm.taobao.org"].find((s) => registry.includes(s))) {
45
+ mirror = "https://npmmirror.com/mirrors/electron";
46
+ }
47
+ }
48
+ return mirror;
49
+ }
50
+ function getBuilderConfig(options, resolvedConfig) {
51
+ var _a;
52
+ createPkg(options, resolvedConfig);
53
+ const config = {
54
+ directories: {
55
+ buildResources: "electron/build",
56
+ app: _path2.default.dirname(resolvedConfig.build.outDir),
57
+ output: "release/${version}"
58
+ },
59
+ files: ["main", "preload", "renderer"],
60
+ artifactName: "${productName}-${version}-${os}-${arch}.${ext}",
61
+ electronDownload: {
62
+ mirror: getMirror()
63
+ },
64
+ electronLanguages: ["zh-CN", "en-US"],
65
+ win: {
66
+ target: [
67
+ {
68
+ target: "nsis",
69
+ arch: ["x64"]
70
+ }
71
+ ]
72
+ },
73
+ mac: {
74
+ target: ["dmg"]
75
+ },
76
+ linux: {
77
+ target: ["zip"]
78
+ },
79
+ nsis: {
80
+ oneClick: false,
81
+ perMachine: false,
82
+ allowToChangeInstallationDirectory: true,
83
+ deleteAppDataOnUninstall: false
84
+ }
85
+ };
86
+ const { appId, productName } = options.builder || {};
87
+ return _lodashmerge2.default.call(void 0, config, { appId, productName }, (_a = options.builder) == null ? void 0 : _a.builderConfig);
88
+ }
89
+ function createPkg(options, resolvedConfig) {
90
+ var _a, _b;
91
+ const externals = options.external || [];
92
+ const viteExternals = (_a = resolvedConfig.build.rollupOptions) == null ? void 0 : _a.external;
93
+ if (Array.isArray(viteExternals)) {
94
+ externals.push(...viteExternals);
95
+ } else if (typeof viteExternals === "string") {
96
+ externals.push(viteExternals);
97
+ }
98
+ const pkg = readJson(_path2.default.join(process.cwd(), "package.json"));
99
+ if (!pkg) {
100
+ throw new Error(`package.json not found in ${process.cwd()}`);
101
+ }
102
+ const outDir = _path2.default.dirname(resolvedConfig.build.outDir);
103
+ const newPkg = {
104
+ name: pkg.name,
105
+ version: pkg.version,
106
+ description: pkg.description,
107
+ type: pkg.type || "commonjs",
108
+ author: getAuthor(pkg.author),
109
+ main: pkg.main ? pkg.main.replace("./", "").substring(pkg.main.indexOf(outDir) + outDir.length - 1) : `main/index.${((_b = options == null ? void 0 : options.main) == null ? void 0 : _b.format) === "esm" ? "" : "m"}js`,
110
+ dependencies: getDeps()
111
+ };
112
+ writeJson(_path2.default.join(outDir, "package.json"), newPkg);
113
+ function getAuthor(author) {
114
+ const uname = _os2.default.userInfo().username;
115
+ if (!author) {
116
+ return uname;
117
+ } else if (typeof author === "string") {
118
+ return author;
119
+ } else if (typeof author === "object") {
120
+ if (!author.name) {
121
+ return uname;
122
+ }
123
+ const email = author.email ? ` <${author.email}>` : "";
124
+ return `${author.name}${email}`;
125
+ }
126
+ return uname;
127
+ }
128
+ function checkDepName(rules, name) {
129
+ return !!rules.find((s) => {
130
+ if (typeof s === "string") {
131
+ return s.includes(name);
132
+ } else {
133
+ return s.test(name);
134
+ }
135
+ });
136
+ }
137
+ function getDeps() {
138
+ const deps = pkg.dependencies || {};
139
+ const newDeps = {};
140
+ Object.keys(deps).forEach((name) => {
141
+ if (checkDepName(externals, name)) {
142
+ newDeps[name] = deps[name];
143
+ }
144
+ });
145
+ return newDeps;
146
+ }
147
+ return newPkg;
148
+ }
149
+ async function runElectronBuilder(options, resolvedConfig) {
150
+ const DIST_PATH = _path2.default.join(_process.cwd.call(void 0, ), _path2.default.dirname(resolvedConfig.build.outDir));
151
+ _shelljs2.default.exec(`cd ${DIST_PATH} && npm install`);
152
+ const config = getBuilderConfig(options, resolvedConfig);
153
+ const { build } = await Promise.resolve().then(() => _interopRequireWildcard(require("electron-builder")));
154
+ await build({
155
+ config
156
+ });
157
+ }
158
+
8
159
  // src/constants.ts
9
160
  var PLUGIN_NAME = "@tomjs:electron";
161
+ var PACKAGE_NAME = "@tomjs/vite-plugin-electron";
10
162
 
11
163
  // src/main.ts
12
- var _child_process = require('child_process');
164
+
13
165
  var _electron = require('electron'); var _electron2 = _interopRequireDefault(_electron);
14
166
  var _treekill = require('tree-kill'); var _treekill2 = _interopRequireDefault(_treekill);
15
167
  var _tsup = require('tsup');
@@ -149,15 +301,6 @@ async function runBuild(options) {
149
301
  }
150
302
  }
151
303
 
152
- // src/utils.ts
153
-
154
- var _module = require('module');
155
- function readJson(path2) {
156
- if (_fs2.default.existsSync(path2)) {
157
- return JSON.parse(_fs2.default.readFileSync(path2, "utf8"));
158
- }
159
- }
160
-
161
304
  // src/index.ts
162
305
  var isDev = process.env.NODE_ENV === "development";
163
306
  function getPkg() {
@@ -228,9 +371,10 @@ function geNumberBooleanValue(value) {
228
371
  const v = Number(value);
229
372
  return Number.isNaN(v) ? void 0 : v;
230
373
  }
231
- function vitePluginElectron(options) {
374
+ function useElectronPlugin(options) {
232
375
  const opts = preMergeOptions(options);
233
376
  let isServer = false;
377
+ let resolvedConfig;
234
378
  return {
235
379
  name: PLUGIN_NAME,
236
380
  config(config, env) {
@@ -273,6 +417,7 @@ function vitePluginElectron(options) {
273
417
  configResolved(config) {
274
418
  opts.debug = config.env.APP_ELECTRON_DEBUG ? !!config.env.APP_ELECTRON_DEBUG : opts.debug;
275
419
  opts.inspect = config.env.APP_ELECTRON_INSPECT ? geNumberBooleanValue(config.env.APP_ELECTRON_INSPECT) : opts.inspect;
420
+ resolvedConfig = config;
276
421
  },
277
422
  configureServer(server) {
278
423
  if (!server || !server.httpServer) {
@@ -285,13 +430,7 @@ function vitePluginElectron(options) {
285
430
  const hostname = family === "IPv6" ? `[${address}]` : address;
286
431
  const protocol = server.config.server.https ? "https" : "http";
287
432
  process.env.APP_DEV_SERVER_URL = `${protocol}://${hostname}:${port}`;
288
- const DEBUG_PATH = _path2.default.resolve(
289
- _process.cwd.call(void 0, ),
290
- "node_modules",
291
- "@tomjs",
292
- "vite-plugin-electron",
293
- "debug"
294
- );
433
+ const DEBUG_PATH = _path2.default.resolve(_process.cwd.call(void 0, ), "node_modules", PACKAGE_NAME, "debug");
295
434
  if (!_fs2.default.existsSync(DEBUG_PATH)) {
296
435
  _fs.mkdirSync.call(void 0, DEBUG_PATH, { recursive: true });
297
436
  }
@@ -302,15 +441,19 @@ ${env}`);
302
441
  });
303
442
  },
304
443
  async closeBundle() {
444
+ var _a;
305
445
  if (isServer) {
306
446
  return;
307
447
  }
308
448
  await runBuild(opts);
449
+ if (opts.recommended && ((_a = opts.builder) == null ? void 0 : _a.enable)) {
450
+ await runElectronBuilder(opts, resolvedConfig);
451
+ }
309
452
  }
310
453
  };
311
454
  }
312
- var src_default = vitePluginElectron;
455
+ var src_default = useElectronPlugin;
313
456
 
314
457
 
315
458
 
316
- exports.default = src_default; exports.vitePluginElectron = vitePluginElectron;
459
+ exports.default = src_default; exports.useElectronPlugin = useElectronPlugin;
package/dist/index.mjs CHANGED
@@ -1,12 +1,163 @@
1
1
  // src/index.ts
2
2
  import fs2, { mkdirSync, writeFileSync } from "fs";
3
- import { cwd } from "process";
3
+ import { cwd as cwd2 } from "process";
4
4
  import cloneDeep from "lodash.clonedeep";
5
- import merge from "lodash.merge";
5
+ import merge2 from "lodash.merge";
6
+ import path2 from "path";
7
+
8
+ // src/builder.ts
9
+ import os from "os";
6
10
  import path from "path";
11
+ import { cwd } from "process";
12
+ import merge from "lodash.merge";
13
+ import shell from "shelljs";
14
+
15
+ // src/utils.ts
16
+ import { spawnSync } from "child_process";
17
+ import fs from "fs";
18
+ function readJson(path3) {
19
+ if (fs.existsSync(path3)) {
20
+ return JSON.parse(fs.readFileSync(path3, "utf8"));
21
+ }
22
+ }
23
+ function writeJson(path3, data) {
24
+ fs.writeFileSync(path3, JSON.stringify(data, null, 2), "utf8");
25
+ }
26
+ function exec(command, args, options) {
27
+ return spawnSync(command, args, Object.assign({ encoding: "utf8" }, options));
28
+ }
29
+
30
+ // src/builder.ts
31
+ function getMirror() {
32
+ let mirror = process.env.ELECTRON_MIRROR;
33
+ if (mirror) {
34
+ return mirror;
35
+ }
36
+ const res = exec(os.platform() === "win32" ? "npm.cmd" : "npm", ["config", "get", "registry"]);
37
+ if (res.status === 0) {
38
+ let registry = res.stdout;
39
+ if (!registry) {
40
+ return;
41
+ }
42
+ registry = registry.trim();
43
+ if (registry && ["registry.npmmirror.com", "registry.npm.taobao.org"].find((s) => registry.includes(s))) {
44
+ mirror = "https://npmmirror.com/mirrors/electron";
45
+ }
46
+ }
47
+ return mirror;
48
+ }
49
+ function getBuilderConfig(options, resolvedConfig) {
50
+ var _a;
51
+ createPkg(options, resolvedConfig);
52
+ const config = {
53
+ directories: {
54
+ buildResources: "electron/build",
55
+ app: path.dirname(resolvedConfig.build.outDir),
56
+ output: "release/${version}"
57
+ },
58
+ files: ["main", "preload", "renderer"],
59
+ artifactName: "${productName}-${version}-${os}-${arch}.${ext}",
60
+ electronDownload: {
61
+ mirror: getMirror()
62
+ },
63
+ electronLanguages: ["zh-CN", "en-US"],
64
+ win: {
65
+ target: [
66
+ {
67
+ target: "nsis",
68
+ arch: ["x64"]
69
+ }
70
+ ]
71
+ },
72
+ mac: {
73
+ target: ["dmg"]
74
+ },
75
+ linux: {
76
+ target: ["zip"]
77
+ },
78
+ nsis: {
79
+ oneClick: false,
80
+ perMachine: false,
81
+ allowToChangeInstallationDirectory: true,
82
+ deleteAppDataOnUninstall: false
83
+ }
84
+ };
85
+ const { appId, productName } = options.builder || {};
86
+ return merge(config, { appId, productName }, (_a = options.builder) == null ? void 0 : _a.builderConfig);
87
+ }
88
+ function createPkg(options, resolvedConfig) {
89
+ var _a, _b;
90
+ const externals = options.external || [];
91
+ const viteExternals = (_a = resolvedConfig.build.rollupOptions) == null ? void 0 : _a.external;
92
+ if (Array.isArray(viteExternals)) {
93
+ externals.push(...viteExternals);
94
+ } else if (typeof viteExternals === "string") {
95
+ externals.push(viteExternals);
96
+ }
97
+ const pkg = readJson(path.join(process.cwd(), "package.json"));
98
+ if (!pkg) {
99
+ throw new Error(`package.json not found in ${process.cwd()}`);
100
+ }
101
+ const outDir = path.dirname(resolvedConfig.build.outDir);
102
+ const newPkg = {
103
+ name: pkg.name,
104
+ version: pkg.version,
105
+ description: pkg.description,
106
+ type: pkg.type || "commonjs",
107
+ author: getAuthor(pkg.author),
108
+ main: pkg.main ? pkg.main.replace("./", "").substring(pkg.main.indexOf(outDir) + outDir.length - 1) : `main/index.${((_b = options == null ? void 0 : options.main) == null ? void 0 : _b.format) === "esm" ? "" : "m"}js`,
109
+ dependencies: getDeps()
110
+ };
111
+ writeJson(path.join(outDir, "package.json"), newPkg);
112
+ function getAuthor(author) {
113
+ const uname = os.userInfo().username;
114
+ if (!author) {
115
+ return uname;
116
+ } else if (typeof author === "string") {
117
+ return author;
118
+ } else if (typeof author === "object") {
119
+ if (!author.name) {
120
+ return uname;
121
+ }
122
+ const email = author.email ? ` <${author.email}>` : "";
123
+ return `${author.name}${email}`;
124
+ }
125
+ return uname;
126
+ }
127
+ function checkDepName(rules, name) {
128
+ return !!rules.find((s) => {
129
+ if (typeof s === "string") {
130
+ return s.includes(name);
131
+ } else {
132
+ return s.test(name);
133
+ }
134
+ });
135
+ }
136
+ function getDeps() {
137
+ const deps = pkg.dependencies || {};
138
+ const newDeps = {};
139
+ Object.keys(deps).forEach((name) => {
140
+ if (checkDepName(externals, name)) {
141
+ newDeps[name] = deps[name];
142
+ }
143
+ });
144
+ return newDeps;
145
+ }
146
+ return newPkg;
147
+ }
148
+ async function runElectronBuilder(options, resolvedConfig) {
149
+ const DIST_PATH = path.join(cwd(), path.dirname(resolvedConfig.build.outDir));
150
+ shell.exec(`cd ${DIST_PATH} && npm install`);
151
+ const config = getBuilderConfig(options, resolvedConfig);
152
+ const { build } = await import("electron-builder");
153
+ await build({
154
+ config
155
+ });
156
+ }
7
157
 
8
158
  // src/constants.ts
9
159
  var PLUGIN_NAME = "@tomjs:electron";
160
+ var PACKAGE_NAME = "@tomjs/vite-plugin-electron";
10
161
 
11
162
  // src/main.ts
12
163
  import { spawn } from "child_process";
@@ -149,18 +300,10 @@ async function runBuild(options) {
149
300
  }
150
301
  }
151
302
 
152
- // src/utils.ts
153
- import fs from "fs";
154
- function readJson(path2) {
155
- if (fs.existsSync(path2)) {
156
- return JSON.parse(fs.readFileSync(path2, "utf8"));
157
- }
158
- }
159
-
160
303
  // src/index.ts
161
304
  var isDev = process.env.NODE_ENV === "development";
162
305
  function getPkg() {
163
- const pkgFile = path.resolve(process.cwd(), "package.json");
306
+ const pkgFile = path2.resolve(process.cwd(), "package.json");
164
307
  if (!fs2.existsSync(pkgFile)) {
165
308
  throw new Error("Main file is not specified, and no package.json found");
166
309
  }
@@ -185,7 +328,7 @@ function preMergeOptions(options) {
185
328
  };
186
329
  }
187
330
  };
188
- const opts = merge(
331
+ const opts = merge2(
189
332
  {
190
333
  recommended: true,
191
334
  debug: false,
@@ -206,7 +349,7 @@ function preMergeOptions(options) {
206
349
  const entry = opt.entry;
207
350
  if (entry == void 0) {
208
351
  const filePath = `electron/${prop}/index.ts`;
209
- if (fs2.existsSync(path.join(process.cwd(), filePath))) {
352
+ if (fs2.existsSync(path2.join(process.cwd(), filePath))) {
210
353
  opt.entry = [filePath];
211
354
  }
212
355
  } else if (typeof entry === "string") {
@@ -227,9 +370,10 @@ function geNumberBooleanValue(value) {
227
370
  const v = Number(value);
228
371
  return Number.isNaN(v) ? void 0 : v;
229
372
  }
230
- function vitePluginElectron(options) {
373
+ function useElectronPlugin(options) {
231
374
  const opts = preMergeOptions(options);
232
375
  let isServer = false;
376
+ let resolvedConfig;
233
377
  return {
234
378
  name: PLUGIN_NAME,
235
379
  config(config, env) {
@@ -239,12 +383,12 @@ function vitePluginElectron(options) {
239
383
  opts.main ||= {};
240
384
  opts.preload ||= {};
241
385
  if (opts.recommended) {
242
- opts.main.outDir = path.join(outDir, "main");
243
- opts.preload.outDir = path.join(outDir, "preload");
244
- outDir = path.join(outDir, "renderer");
386
+ opts.main.outDir = path2.join(outDir, "main");
387
+ opts.preload.outDir = path2.join(outDir, "preload");
388
+ outDir = path2.join(outDir, "renderer");
245
389
  } else {
246
- opts.main.outDir ||= path.join("dist-electron", "main");
247
- opts.preload.outDir ||= path.join("dist-electron", "preload");
390
+ opts.main.outDir ||= path2.join("dist-electron", "main");
391
+ opts.preload.outDir ||= path2.join("dist-electron", "preload");
248
392
  }
249
393
  if (isDev) {
250
394
  opts.main.sourcemap ??= true;
@@ -272,6 +416,7 @@ function vitePluginElectron(options) {
272
416
  configResolved(config) {
273
417
  opts.debug = config.env.APP_ELECTRON_DEBUG ? !!config.env.APP_ELECTRON_DEBUG : opts.debug;
274
418
  opts.inspect = config.env.APP_ELECTRON_INSPECT ? geNumberBooleanValue(config.env.APP_ELECTRON_INSPECT) : opts.inspect;
419
+ resolvedConfig = config;
275
420
  },
276
421
  configureServer(server) {
277
422
  if (!server || !server.httpServer) {
@@ -284,32 +429,30 @@ function vitePluginElectron(options) {
284
429
  const hostname = family === "IPv6" ? `[${address}]` : address;
285
430
  const protocol = server.config.server.https ? "https" : "http";
286
431
  process.env.APP_DEV_SERVER_URL = `${protocol}://${hostname}:${port}`;
287
- const DEBUG_PATH = path.resolve(
288
- cwd(),
289
- "node_modules",
290
- "@tomjs",
291
- "vite-plugin-electron",
292
- "debug"
293
- );
432
+ const DEBUG_PATH = path2.resolve(cwd2(), "node_modules", PACKAGE_NAME, "debug");
294
433
  if (!fs2.existsSync(DEBUG_PATH)) {
295
434
  mkdirSync(DEBUG_PATH, { recursive: true });
296
435
  }
297
436
  const env = Object.keys(process.env).filter((s) => s.startsWith("APP_") || s.startsWith("VITE_")).map((s) => `${s}=${process.env[s]}`).join("\n");
298
- writeFileSync(path.join(DEBUG_PATH, ".env"), `NODE_ENV=development
437
+ writeFileSync(path2.join(DEBUG_PATH, ".env"), `NODE_ENV=development
299
438
  ${env}`);
300
439
  await runServe(opts, server);
301
440
  });
302
441
  },
303
442
  async closeBundle() {
443
+ var _a;
304
444
  if (isServer) {
305
445
  return;
306
446
  }
307
447
  await runBuild(opts);
448
+ if (opts.recommended && ((_a = opts.builder) == null ? void 0 : _a.enable)) {
449
+ await runElectronBuilder(opts, resolvedConfig);
450
+ }
308
451
  }
309
452
  };
310
453
  }
311
- var src_default = vitePluginElectron;
454
+ var src_default = useElectronPlugin;
312
455
  export {
313
456
  src_default as default,
314
- vitePluginElectron
457
+ useElectronPlugin
315
458
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomjs/vite-plugin-electron",
3
- "version": "1.3.8",
3
+ "version": "1.3.9-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,11 +40,22 @@
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
+ },
43
53
  "dependencies": {
44
54
  "dayjs": "^1.11.10",
45
55
  "kolorist": "^1.8.0",
46
56
  "lodash.clonedeep": "^4.5.0",
47
57
  "lodash.merge": "^4.6.2",
58
+ "shelljs": "^0.8.5",
48
59
  "tree-kill": "^1.2.2",
49
60
  "tsup": "7.2.0"
50
61
  },
@@ -58,7 +69,7 @@
58
69
  "@types/lodash.clonedeep": "^4.5.9",
59
70
  "@types/lodash.merge": "^4.6.9",
60
71
  "@types/node": "^18.19.3",
61
- "electron": "^28.0.0",
72
+ "@types/shelljs": "^0.8.15",
62
73
  "eslint": "^8.55.0",
63
74
  "husky": "^8.0.3",
64
75
  "lint-staged": "^15.2.0",
@@ -68,19 +79,16 @@
68
79
  "rimraf": "^5.0.5",
69
80
  "stylelint": "^15.11.0",
70
81
  "tsx": "^4.6.2",
71
- "typescript": "~5.2.2",
72
- "vite": "^5.0.7"
82
+ "typescript": "~5.2.2"
73
83
  },
74
84
  "peerDependencies": {
75
85
  "electron": ">=12.0.0",
76
- "vite": ">=2"
86
+ "electron-builder": ">=24.2.0",
87
+ "vite": ">=2.9.0"
77
88
  },
78
- "scripts": {
79
- "dev": "tsup --watch",
80
- "build": "tsup",
81
- "lint": "run-s lint:eslint lint:stylelint lint:prettier",
82
- "lint:eslint": "eslint \"{src,examples}/**/*.{js,cjs,ts,tsx,vue}\" *.{js,cjs,ts} --fix --cache",
83
- "lint:stylelint": "stylelint \"examples/**/*.{css,scss,less,vue,html}\" --fix --cache",
84
- "lint:prettier": "prettier --write ."
89
+ "peerDependenciesMeta": {
90
+ "electron-builder": {
91
+ "optional": true
92
+ }
85
93
  }
86
- }
94
+ }