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 all 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
2 changes: 2 additions & 0 deletions .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
```
42 changes: 42 additions & 0 deletions packages/plugin-electron/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"name": "@umijs/plugin-electron",
"version": "0.1.0-9",
"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": {
"@babel/plugin-syntax-top-level-await": "^7.14.5",
"babel-plugin-import-to-window-require": "*",
"electron": "^14",
"electron-builder": "22.10.5",
"father-build": "1.20.5-8",
"ora": "^5",
"rimraf": "^3.0.2"
},
"devDependencies": {
"@types/rimraf": "^3.0.2"
}
}
41 changes: 41 additions & 0 deletions packages/plugin-electron/src/buildElectron.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { rimraf } from '@umijs/utils';
import {
build,
Platform,
createTargets,
Configuration,
} from 'electron-builder';
import lodash from 'lodash';
import { join } from 'path';
import { TMP_DIR_PRODUCTION } from './constants';

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];

return build({
targets: createTargets(targets),
config: lodash.merge(
{
directories: { output: '../dist' },
} as Configuration,
{
dmg: {
title: `\${productName}-\${version}`,
artifactName: `\${productName}-\${version}.\${ext}`,
},
nsis: {
artifactName: `\${productName}-setup-\${version}.\${ext}`,
},
} as Configuration,
builderConfig as unknown as Configuration,
customBuilderConfig || {},
),
projectDir: join(process.cwd(), TMP_DIR_PRODUCTION),
});
};
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://registry.npmmirror.com/binary.html?path=electron/',
},
productName,
files: ['./**'],
mac: {
category: 'public.app-category.developer-tools',
target: 'dmg',
},
dmg: {},
win: {
target: 'nsis',
},
nsis: {
oneClick: false,
allowToChangeInstallationDirectory: true,
},
};
74 changes: 74 additions & 0 deletions packages/plugin-electron/src/config/father.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
const { resolve } = require('path');
const { writeFileSync } = require('fs');
const { getPkgName } = require('../utils/getPkgName');

const TMP_DIR = '.electron';
const TMP_DIR_PRODUCTION = '.electron-production';

const getTmpDir = (mode) => {
return mode === 'development' ? TMP_DIR : TMP_DIR_PRODUCTION;
};

const deps = new Set(); // 搜集所有依赖
const depsOfFile = {}; // 搜集文件依赖
const filesOfDep = {}; // 搜集依赖所在文件
/**
* @param {'production' | 'development'} mode
* @param {Set} toGenerateDeps
*/
const generateDeps = (mode, toGenerateDeps) => {
writeFileSync(
resolve(process.cwd(), `${getTmpDir(mode)}/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 (mode) => ({
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(mode, deps);
},
},
],
],
});
2 changes: 2 additions & 0 deletions packages/plugin-electron/src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const TMP_DIR = '.electron';
export const TMP_DIR_PRODUCTION = '.electron-production';
45 changes: 45 additions & 0 deletions packages/plugin-electron/src/electronManager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import electron from 'electron';
import proc, { ChildProcess } from 'child_process';
import yParser from 'yargs-parser';
import { log } from './utils';
const args = yParser(process.argv.slice(2));

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

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();
}
}
82 changes: 82 additions & 0 deletions packages/plugin-electron/src/fatherBuild.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { existsSync, readFileSync } from 'fs';
import path, { resolve } from 'path';
import { TMP_DIR, TMP_DIR_PRODUCTION } from './constants';
// @ts-ignore
import build from 'father-build';
import fatherBuildArgs from './config/father';

export type Mode = 'development' | 'production';

export const getTmpDir = (mode: Mode) => {
return mode === 'development' ? TMP_DIR : TMP_DIR_PRODUCTION;
};

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

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

type WatchOpts = {
beforeBuild?: () => void;
onBuildComplete?: () => 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(), getTmpDir(opts.mode), 'main'),
mode: opts.mode,
};
}
private getBuildArgs = () => {
console.log('get father build args,mode: ', this.opts.mode);
return {
...fatherBuildArgs(this.opts.mode),
silent: true,
src: this.opts.src,
output: this.opts.output,
};
};
watch = async (opts: WatchOpts): Promise<{ exit: () => void }> => {
const dispose = await build({
watch: true,
beforeBuild: opts.beforeBuild,
onBuildComplete: opts.onBuildComplete,
cwd: process.cwd(),
buildArgs: this.getBuildArgs(),
});
return {
exit: () => {
dispose();
},
};
};
build = async () => {
try {
await build({
cwd: process.cwd(),
buildArgs: this.getBuildArgs(),
});
} catch (error) {
console.log(error);
}
};
static getUserConfig(): string | undefined {
const userConfigPath = path.resolve(process.cwd(), '.fatherrc.js');
if (existsSync(userConfigPath)) {
return readFileSync(userConfigPath, 'utf-8');
}
return;
}
}

export { FatherBuildCli };
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
module.exports = function () {
return {
visitor: {
CallExpression: {
enter(path, state) {
const { onCollect } = state.opts;
const { node } = path;
// require & import()
if (
(node.callee.type === 'Identifier' &&
node.callee.name === 'require') ||
node.callee.type === 'Import'
) {
const dependencies = node.arguments
.map(({ type, value }) => {
if (type === 'StringLiteral') return value;
})
.filter(Boolean);
if (dependencies[0]) {
onCollect(state.filename, dependencies[0]);
}
}
},
},
ImportDeclaration: {
enter(path, state) {
const { node } = path;
const { onCollect } = state.opts;
onCollect(state.filename, node.source.value);
},
},
},
};
};
Loading