main.js 2.4 KB

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