如何设置基于AngularCLI的Electron项目,具有调试/实时重载?

时间:2017-03-08 15:07:12

标签: angular electron angular-cli

我正在尝试设置一个AngularCLI项目,该项目可以在浏览器中通过电子运行。

我找到了一些很好的教程,比如这篇文章:

http://www.blog.bdauria.com/?p=806

但是,我无法找到或找出允许在电子项目中进行实时重新加载和调试的设置。

1 个答案:

答案 0 :(得分:0)

假设您正在使用@angular/cli

  • electron文件夹
  • 旁边创建一个文件夹src
  • 在此文件夹中,创建文件electron.js

将以下内容粘贴到其中:

const {app, BrowserWindow} = require('electron');

// keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected
let win;

function createWindow() {
  // create the browser window
  win = new BrowserWindow();
  win.maximize();

  // and load the index.html of the app
  win.loadURL(`file://${__dirname}/index.html`);

  // ----------------------------------------------------------------
  //           THIS IS WHAT YOU'RE LOOKING FOR DEBUGGING
  // open the DevTools
  win.webContents.openDevTools()
  // ----------------------------------------------------------------

  // emitted when the window is closed
  win.on('closed', () => {
    // fereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element
    win = null;
  });
};

// yhis method will be called when Electron has finished
// initialization and is ready to create browser windows
// some APIs can only be used after this event occurs
app.on('ready', createWindow);

// quit when all windows are closed
app.on('window-all-closed', () => {
  // on macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  // on macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open
  if (win === null) {
    createWindow();
  }
});
  • 在同一文件夹中,创建文件generate-package-json.json。这样我们就可以自动为我们的电子应用程序生成包:

文件:

const fs = require('fs');

const package = `{ "name": "${ require('../package.json').name}", "version": "${ require('../package.json').version}", "main": "electron.js" }`;

fs.writeFile('./dist/package.json', package, err => {
  if (err) {
    return console.log(err);
  }
});

然后在你的package.json中:

{
  ...
  scripts: {
    "build-electron": "npm run build -- -bh='./'; node ./electron/generate-package-json.js; cp ./electron/electron.js dist/",
    "electron": "npm run build-electron; electron dist/"
  }
  ...
}

最后,运行npm run electron