Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] feat: electron plugin #764

Open
wants to merge 19 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file.
2 changes: 2 additions & 0 deletions packages/plugin-electron/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
electron-mirror=https://npm.taobao.org/mirrors/electron/
electron-builder-binaries-mirror=http://npm.taobao.org/mirrors/electron-builder-binaries/
19 changes: 19 additions & 0 deletions packages/plugin-electron/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# @umijs/plugin-electron

> @umijs/plugin-electron.

See our website [@umijs/plugin-electron](https://umijs.org/plugins/plugin-electron) for more information.

## Install

Using npm:

```bash
$ npm install --save-dev @umijs/plugin-electron
```

or using yarn:

```bash
$ yarn add @umijs/plugin-electron --dev
```
40 changes: 40 additions & 0 deletions packages/plugin-electron/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
"name": "@umijs/plugin-electron",
"version": "0.1.0-0",
"description": "@umijs/plugin-electron",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"files": [
"lib",
"src"
],
"repository": {
"type": "git",
"url": "https://github.com/umijs/plugins"
xiaohuoni marked this conversation as resolved.
Show resolved Hide resolved
},
"keywords": [
"umi"
],
"authors": [
"xiefengnian <[email protected]> (https://github.com/xiefengnian)"
],
"license": "MIT",
"bugs": "http://github.com/umijs/plugins/issues",
"homepage": "https://github.com/umijs/plugins/tree/master/packages/plugin-dva#readme",
xiaohuoni marked this conversation as resolved.
Show resolved Hide resolved
"peerDependencies": {
"umi": "3.x"
},
"publishConfig": {
"access": "public"
},
"dependencies": {
"father-build" : "1.20.5-5",
"electron" : "^14",
"electron-builder": "22.10.5",
"babel-plugin-import-to-window-require" : "*",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

不要用 *

"rimraf": "^3.0.2"
},
"devDependencies": {
"@types/rimraf": "^3.0.2"
}
}
50 changes: 50 additions & 0 deletions packages/plugin-electron/src/buildElectron.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { rimraf } from '@umijs/utils';
import {
build,
Platform,
createTargets,
Configuration,
} from 'electron-builder';
import lodash from 'lodash';
import { join } from 'path';
import { generateMd5 } from './utils';

const builderConfig = require('./config/electron-builder.config');
export const buildElectron = (customBuilderConfig?: Configuration) => {
rimraf.sync(join(process.cwd(), 'dist'));

const targets =
process.platform === 'darwin'
? [Platform.MAC, Platform.WINDOWS]
: [Platform.WINDOWS];

build({
targets: createTargets(targets),
config: lodash.merge(
customBuilderConfig || {},
builderConfig as unknown as Configuration,
{
electronVersion: '14.0.0',
directories: { output: 'dist' },
} as Configuration,
{
dmg: {
title: `\${productName}-\${version}`,
artifactName: `\${productName}-\${version}.\${ext}`,
},
nsis: {
artifactName: `\${productName}-setup-\${version}.\${ext}`,
},
} as Configuration,
),
})
.then((res) => {
generateMd5(res);
})
.catch((err) => {
console.log(err);
})
.finally(() => {
process.send?.('exit');
});
};
31 changes: 31 additions & 0 deletions packages/plugin-electron/src/check.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { resolve } from 'path';
import chalk from 'chalk';
import yParser from 'yargs-parser';
import { TMP_DIR } from './constants';
const args = yParser(process.argv.slice(2));

const checkMainField = () => {
const userPackageJson = require(resolve(process.cwd(), './package.json'));
const { main } = userPackageJson;
if (!main) {
console.log(
chalk.bgRedBright('Error') +
` ${chalk.red('main')} field in package.json must not be empty`,
);
throw new Error('empty entry');
} else {
if (!args.output && main !== `${TMP_DIR}/main/index.js`) {
console.log(
chalk.bgRedBright('Error') +
` ${chalk.red('main')} field in package.json must be ${chalk.red(
`"${TMP_DIR}/main/index.js"`,
)}`,
);
throw new Error('wrong entry');
}
}
};

export const check = () => {
checkMainField();
};
23 changes: 23 additions & 0 deletions packages/plugin-electron/src/config/electron-builder.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { join } from 'path';

const { productName } = require(join(process.cwd(), 'package.json'));

module.exports = {
electronDownload: {
mirror: 'https://npm.taobao.org/mirrors/electron/',
},
productName,
files: ['.electron/**'],
mac: {
category: 'public.app-category.developer-tools',
target: 'dmg',
},
dmg: {},
win: {
target: 'nsis',
},
nsis: {
oneClick: false,
allowToChangeInstallationDirectory: true,
},
};
67 changes: 67 additions & 0 deletions packages/plugin-electron/src/config/father.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
const { resolve } = require('path');
const { writeFileSync } = require('fs');
const { getPkgName } = require('../utils/getPkgName');

const deps = new Set(); // 搜集所有依赖
const depsOfFile = {}; // 搜集文件依赖
const filesOfDep = {}; // 搜集依赖所在文件
/**
*
* @param {Set} toGenerateDeps
*/
const generateDeps = (toGenerateDeps) => {
writeFileSync(
resolve(process.cwd(), '.electron/dependencies.json'),
JSON.stringify(
{
all: Array.from(toGenerateDeps),
files: Object.keys(depsOfFile).reduce((memo, current) => {
return {
...memo,
[current]: Array.from(depsOfFile[current]),
};
}, {}),
deps: Object.keys(filesOfDep).reduce((memo, current) => {
return {
...memo,
[current]: Array.from(filesOfDep[current]),
};
}, {}),
},
null,
2,
),
);
};

export default {
entry: resolve(process.cwd(), 'src/main/index.ts'),
cjs: {
type: 'babel',
},
target: 'node',
disableTypeCheck: true,
extraBabelPlugins: [
[
require('../features/package-analyze/babel-plugin-import-analyze'),
{
onCollect: (filename, depName) => {
let finalDepName = getPkgName(depName);
if (!finalDepName) {
return;
}
deps.add(finalDepName);
if (!depsOfFile[filename]) {
depsOfFile[filename] = new Set();
}
if (!filesOfDep[finalDepName]) {
filesOfDep[finalDepName] = new Set();
}
filesOfDep[finalDepName].add(filename);
depsOfFile[filename].add(finalDepName);
generateDeps(deps);
},
},
],
],
};
1 change: 1 addition & 0 deletions packages/plugin-electron/src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const TMP_DIR = '.electron';
43 changes: 43 additions & 0 deletions packages/plugin-electron/src/electronManager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import electron from 'electron';
import proc, { ChildProcess } from 'child_process';
import { resolve } from 'path';
import yParser from 'yargs-parser';
import { log } from './utils';
const args = yParser(process.argv.slice(2));

const appPath = resolve(process.cwd());

export class ElectronProcessManager {
electronProcess: ChildProcess | undefined;
start() {
this.kill();
const childProc = proc.spawn(
electron as unknown as string,
args.inspect ? [`--inspect=${args.inspect}`, appPath] : [appPath],
{
stdio: 'pipe',
env: {
...process.env,
FORCE_COLOR: '1',
},
},
);

childProc.on('error', (err) => {
log.error('electron process error!');
console.log(err);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
childProc.kill();
process.exit(1);
});

childProc.stdout?.pipe(process.stdout);
childProc.stderr?.pipe(process.stderr);

this.electronProcess = childProc;
}

kill() {
this.electronProcess?.kill();
}
}
107 changes: 107 additions & 0 deletions packages/plugin-electron/src/fatherCli.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { fork } from 'child_process';
import { existsSync, readFileSync } from 'fs';
import path, { resolve, join } from 'path';
import chokidar from 'chokidar';
import { debounce } from 'lodash';
import { TMP_DIR } from './constants';
import { log } from './utils';

type FatherBuildCliOpts = {
configPath?: string;
src?: string;
output?: string;
};

export type WatchReturnType = {
exit: () => void;
};

type WatchOpts = {
onBuild?: () => void;
};

class FatherBuildCli {
private opts: FatherBuildCliOpts;
constructor(opts: FatherBuildCliOpts) {
this.opts = {
configPath: opts.configPath,
src: opts.src || resolve(process.cwd(), 'src', 'main'),
output: opts.output || resolve(process.cwd(), TMP_DIR, 'main'),
};
}
watch(opts: WatchOpts): { exit: () => void } {
const proc = fork(
join(require.resolve('father-build'), '../../bin/father-build.js'),
[
`--src=${this.opts.src}`,
`--output=${this.opts.output}`,
'-w',
`--config=${this.opts.configPath}`,
],
{
stdio: 'pipe',
env: { ...process.env, FORCE_COLOR: '1' },
cwd: process.cwd(),
},
);
proc.stdout?.pipe(process.stdout);
proc.stderr?.pipe(process.stderr);
const watchDir = join(process.cwd(), TMP_DIR, 'main');
const watcher = chokidar.watch(watchDir, { ignoreInitial: true }).on(
'all',
debounce(() => {
opts.onBuild?.();
}, 500),
);
log.info(`watching ${watchDir}`);
return {
exit: () => {
watcher.close().then(() => {
proc.kill();
});
},
};
}
build(): Promise<boolean> {
return new Promise((resolve, reject) => {
const args = this.opts.configPath
? [`--config=${this.opts.configPath}`]
: [];
const proc = fork(
join(require.resolve('father-build'), '../../bin/father-build.js'),
args.concat([
`--output=${this.opts?.output}`,
`--src=${this.opts.src}`,
]),
{
stdio: 'pipe',
env: { ...process.env, FORCE_COLOR: '1' },
},
);
proc.stdout?.pipe(process.stdout);
proc.stderr?.pipe(process.stderr);
const messages: unknown[] = [];
proc.on('message', (msg) => {
messages.push(msg);
});
proc.on('close', (code) => {
if (code !== 0) {
reject(messages.join('\n'));
}
resolve(true);
});
proc.on('error', (err) => {
throw err;
});
});
}
static getUserConfig(): string | undefined {
const userConfigPath = path.resolve(process.cwd(), '.fatherrc.js');
if (existsSync(userConfigPath)) {
return readFileSync(userConfigPath, 'utf-8');
}
return;
}
}

export { FatherBuildCli };
Loading