先介绍下electron,\

Electron.js 是一个流行的平台,用于使用 JavaScript,HTML 和 CSS 构建适用于 Windows,Linux 和 macOS 的跨平台桌面应用程序。

需要了解typescript 和 angular

需要先安装node.js 和npm 

步骤如下:

首先,先构建一个单纯的angular应用,可以正常运行

然后,

先安装electron

npm install--save-dev electron

接下来在根目录创建一个main.js 文件并添加一下代码

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

const url = require("url");

const path = require("path");

let mainWindow

function createWindow () {

  mainWindow = new BrowserWindow({

    width: 800,

    height: 600,

    webPreferences: { nodeIntegration: true }

  })

  mainWindow.loadURL(

    url.format({

      pathname: path.join(__dirname, `/dist/index.html`),

      protocol: "file:", slashes: true }) );

      // Open the DevTools.

       mainWindow.webContents.openDevTools()

      mainWindow.on('closed', function () {

        mainWindow = null

      })

  }

  app.on('ready', createWindow)

  app.on('window-all-closed',

    function () {

      if (process.platform !== 'darwin') app.quit() }

    )

   app.on('activate', function () {

    if (mainWindow === null)   

      createWindow() 

    })
此代码只是创建一个GUI窗口,并在我们构建Angular应用程序后加载该index.html 文件dist夹下应该可用的文件

打开package.json,添加“main":"main.js"为主要入口点

 

 接下来,需要在构建 Angular 项目后启动 Electron 

 

 

ng build --base-href ./ 命令的一部分构建 Angular 应用程序并将基本 href 设置为./。

electron . 命令的一部分从当前目录启动我们的 Electron 应用程序。

现在执行npm run start:electron .将会启动electron 应用程序

GUI 窗口将打开,在控制台中,您将看到 不允许加载本地资源:/electron-angular-demo/dist/index.html 错误。

Electron 无法从 dist 文件夹加载文件,因为它根本不存在。如果您查看项目的文件夹,您将看到 Angular CLI 在 dist/electron-angular-demo 文件夹而不仅仅是 dist 文件夹中构建您的应用程序

在我们的 main.js 文件中,我们告诉 Electron index.html 在 dist 没有子文件夹的文件夹中查找文件:

 

 

 

__dirname 指的是我们运行 Electron 的当前文件夹。

我们使用该 path.join()方法将当前文件夹的/dist/index.html 路径与路径连接起来。

可以更改路径的第二部分,/dist/electron-angular-demo/index.html 或者更好的是,更改 Angular 配置以输出文件 dist 夹中的文件而不使用子文件夹。
打开 angular.json 文件,找到 projects → architect → build → options → outputPath 密钥并将其值更改 dist/electron-angular-demo 为 dist:

 

 

再次执行 npm run start:electron

 

该文章来源于 https://ld246.com/article/1559209582761

 

posted on 2021-06-24 17:34  祁祁  阅读(625)  评论(0编辑  收藏  举报