compilerElectron.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import rollup, { OutputOptions } from 'rollup';
  2. import chalk from 'chalk';
  3. import ora from 'ora';
  4. import waitOn from 'wait-on';
  5. import net from 'net';
  6. import { URL } from 'url';
  7. import minimist from 'minimist';
  8. import electronConnect from 'electron-connect';
  9. import { getRollupOptions } from '../config/rollupElectronConfig';
  10. const argv = minimist(process.argv.slice(2));
  11. const TAG = '[compiler-electron]';
  12. export function startCompilerElectron(port = 80) {
  13. // 因为 vite 不会重定向到 index.html,所以直接写 index.html 路由。
  14. const ELECTRON_URL = `https://localhost:${port}/index.html`;
  15. const spinner = ora(`${TAG} Electron build...`);
  16. const electron = electronConnect.server.create({ stopOnClose: true });
  17. const rollupOptions = getRollupOptions();
  18. function watchFunc() {
  19. // once here, all resources are available
  20. const watcher = rollup.watch(rollupOptions);
  21. watcher.on('change', (filename) => {
  22. const log = chalk.green(`change -- ${filename}`);
  23. console.log(TAG, log);
  24. });
  25. watcher.on('event', (ev) => {
  26. if (ev.code === 'END') {
  27. // init-未启动、started-第一次启动、restarted-重新启动
  28. electron.electronState === 'init' ? electron.start() : electron.restart();
  29. } else if (ev.code === 'ERROR') {
  30. console.log(ev.error);
  31. }
  32. });
  33. }
  34. if (argv.watch) {
  35. waitOn(
  36. {
  37. resources: [ELECTRON_URL],
  38. timeout: 5000,
  39. },
  40. (err) => {
  41. if (err) {
  42. const { hostname } = new URL(ELECTRON_URL);
  43. const serverSocket = net.connect(port, hostname, () => {
  44. watchFunc();
  45. });
  46. serverSocket.on('error', (e) => {
  47. console.log(err);
  48. console.log(e);
  49. process.exit(1);
  50. });
  51. } else {
  52. watchFunc();
  53. }
  54. }
  55. );
  56. } else {
  57. spinner.start();
  58. rollup
  59. .rollup(rollupOptions)
  60. .then((build) => {
  61. spinner.stop();
  62. console.log(TAG, chalk.green('Electron build successed.'));
  63. build.write(rollupOptions.output as OutputOptions);
  64. })
  65. .catch((error) => {
  66. spinner.stop();
  67. console.log(`\n${TAG} ${chalk.red('构建报错')}\n`, error, '\n');
  68. });
  69. }
  70. }