main.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. const {app, BrowserWindow, Menu, shell} = require('electron')
  2. const path = require('path')
  3. const getPort = require('get-port')
  4. const eggLauncher = require('./electron/lanucher')
  5. const setup = require('./electron/index')
  6. setup()
  7. // 主窗口
  8. global.MAIN_WINDOW = null
  9. let options = {
  10. env: 'prod',
  11. eggPort: 7068,
  12. workers: 1
  13. };
  14. for (let i = 0; i < process.argv.length; i++) {
  15. const tmpArgv = process.argv[i];
  16. if (tmpArgv.indexOf('--env=') !== -1) {
  17. options.env = tmpArgv.substr(6);
  18. }
  19. }
  20. ELog.info('options', options);
  21. if (process.mas) app.setName('electron-egg')
  22. app.on('web-contents-created', (e, webContents) => {
  23. webContents.on('new-window', (event, url) => {
  24. event.preventDefault();
  25. shell.openExternal(url);
  26. });
  27. });
  28. async function createWindow () {
  29. MAIN_WINDOW = new BrowserWindow({
  30. width: 800,
  31. height: 600,
  32. minWidth: 800,
  33. minHeight: 600,
  34. webPreferences: {
  35. //webSecurity: false,
  36. nodeIntegration: true,
  37. preload: path.join(__dirname, 'preload.js')
  38. },
  39. //frame: false,
  40. //titleBarStyle: 'hidden'
  41. })
  42. // if (process.platform === 'linux') {
  43. // windowOptions.icon = path.join(__dirname, '/assets/app-icon/png/512.png')
  44. // }
  45. if (options.env === 'prod') {
  46. //隐藏菜单
  47. Menu.setApplicationMenu(null)
  48. }
  49. // loding页
  50. MAIN_WINDOW.loadURL(path.join('file://', __dirname, '/app/public/loading.html'))
  51. // egg服务
  52. setTimeout(function(){
  53. startServer(options)
  54. }, 100)
  55. return MAIN_WINDOW;
  56. }
  57. async function startServer (options) {
  58. let startRes = null;
  59. options.eggPort = await getPort({port: options.eggPort})
  60. let params = {
  61. port: options.eggPort,
  62. title: 'electron-egg',
  63. workers: 1,
  64. env: options.env
  65. }
  66. startRes = await eggLauncher.start(params).then((res) => res, (err) => err)
  67. ELog.info('startRes:', startRes);
  68. if (startRes === 'success') {
  69. let url = 'http://localhost:' + options.eggPort
  70. MAIN_WINDOW.loadURL(url)
  71. return
  72. }
  73. app.relaunch()
  74. }
  75. async function initialize () {
  76. // loadFiles()
  77. app.whenReady().then(() => {
  78. createWindow()
  79. app.on('activate', function () {
  80. if (BrowserWindow.getAllWindows().length === 0) {
  81. createWindow()
  82. }
  83. })
  84. })
  85. app.on('window-all-closed', function () {
  86. if (process.platform !== 'darwin') {
  87. console.log('window-all-closed quit')
  88. app.quit()
  89. }
  90. })
  91. }
  92. initialize()