main.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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/setup')
  6. const config = require('./electron/config').get()
  7. setup()
  8. //return
  9. // 主窗口
  10. global.MAIN_WINDOW = null
  11. for (let i = 0; i < process.argv.length; i++) {
  12. const tmpArgv = process.argv[i]
  13. if (tmpArgv.indexOf('--env=') !== -1) {
  14. config.egg.env = tmpArgv.substr(6)
  15. }
  16. }
  17. if (process.mas) app.setName('electron-egg')
  18. app.on('web-contents-created', (e, webContents) => {
  19. webContents.on('new-window', (event, url) => {
  20. event.preventDefault()
  21. shell.openExternal(url)
  22. });
  23. });
  24. async function createWindow () {
  25. MAIN_WINDOW = new BrowserWindow(config.windowsOption)
  26. // if (process.platform === 'linux') {
  27. // windowOptions.icon = path.join(__dirname, '/assets/app-icon/png/512.png')
  28. // }
  29. if (config.egg.env === 'prod') {
  30. //隐藏菜单
  31. Menu.setApplicationMenu(null)
  32. }
  33. // loding页
  34. MAIN_WINDOW.loadURL(path.join('file://', __dirname, '/app/public/loading.html'))
  35. // egg服务
  36. setTimeout(function(){
  37. startServer(config.egg)
  38. }, 100)
  39. return MAIN_WINDOW
  40. }
  41. async function startServer (options) {
  42. let startRes = null
  43. options.port = await getPort({port: options.port})
  44. ELog.info('config.egg', options)
  45. startRes = await eggLauncher.start(options).then((res) => res, (err) => err)
  46. ELog.info('startRes:', startRes)
  47. if (startRes === 'success') {
  48. let url = 'http://localhost:' + options.port
  49. MAIN_WINDOW.loadURL(url)
  50. return
  51. }
  52. app.relaunch()
  53. }
  54. async function initialize () {
  55. app.whenReady().then(() => {
  56. createWindow()
  57. app.on('activate', function () {
  58. if (BrowserWindow.getAllWindows().length === 0) {
  59. createWindow()
  60. }
  61. })
  62. })
  63. app.on('window-all-closed', function () {
  64. if (process.platform !== 'darwin') {
  65. console.log('window-all-closed quit')
  66. app.quit()
  67. }
  68. })
  69. }
  70. initialize()