build.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * electron 打包
  3. */
  4. const path = require('path');
  5. const rollup = require('rollup');
  6. const argv = require('minimist')(process.argv.slice(2));
  7. const chalk = require('chalk');
  8. const ora = require('ora');
  9. const waitOn = require('wait-on');
  10. const electron = require('electron-connect').server.create({ stopOnClose: true });
  11. require('dotenv').config({ path: path.join(__dirname, '../.env') });
  12. const options = require('./rollup.config');
  13. const net = require('net');
  14. const { URL } = require('url');
  15. const opt = options(argv.env);
  16. const TAG = '[script/build.js]';
  17. const spinner = ora(`${TAG} Electron build...`);
  18. const watchFunc = function () {
  19. // once here, all resources are available
  20. const watcher = rollup.watch(opt);
  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. const resource = `http://localhost:${process.env.PORT}/index.html`; // 因为 vite 不会重定向到 index.html,所以直接写 index.html 路由。
  35. if (argv.watch) {
  36. waitOn(
  37. {
  38. resources: [resource],
  39. timeout: 5000,
  40. },
  41. (err) => {
  42. if (err) {
  43. const { port, hostname } = new URL(resource);
  44. const serverSocket = net.connect(port || 80, hostname, () => {
  45. watchFunc();
  46. });
  47. serverSocket.on('error', (e) => {
  48. console.log(err);
  49. console.log(e);
  50. process.exit(1);
  51. });
  52. } else {
  53. watchFunc();
  54. }
  55. }
  56. );
  57. } else {
  58. spinner.start();
  59. rollup
  60. .rollup(opt)
  61. .then((build) => {
  62. spinner.stop();
  63. console.log(TAG, chalk.green('Electron build successed.'));
  64. build.write(opt.output);
  65. })
  66. .catch((error) => {
  67. spinner.stop();
  68. console.log(`\n${TAG} ${chalk.red('构建报错')}\n`, error, '\n');
  69. });
  70. }