先介紹下electron,\
Electron.js 是一個(gè)流行的平臺(tái),用于使用 JavaScript,HTML 和 CSS 構(gòu)建適用于 Windows,Linux 和 macOS 的跨平臺(tái)桌面應(yīng)用程序。
需要了解typescript 和 angular
需要先安裝node.js 和npm
步驟如下:
首先,先構(gòu)建一個(gè)單純的angular應(yīng)用,可以正常運(yùn)行
然后,
先安裝electron
npm install--save-dev electron
接下來(lái)在根目錄創(chuàng)建一個(gè)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()
})
此代碼只是創(chuàng)建一個(gè)GUI窗口,并在我們構(gòu)建Angular應(yīng)用程序后加載該index.html 文件dist夾下應(yīng)該可用的文件
打開(kāi)package.json,添加“main":"main.js"為主要入口點(diǎn)

接下來(lái),需要在構(gòu)建 Angular 項(xiàng)目后啟動(dòng) Electron

ng build --base-href ./ 命令的一部分構(gòu)建 Angular 應(yīng)用程序并將基本 href 設(shè)置為./。
electron . 命令的一部分從當(dāng)前目錄啟動(dòng)我們的 Electron 應(yīng)用程序。
現(xiàn)在執(zhí)行npm run start:electron .將會(huì)啟動(dòng)electron 應(yīng)用程序
GUI 窗口將打開(kāi),在控制臺(tái)中,您將看到 不允許加載本地資源:/electron-angular-demo/dist/index.html 錯(cuò)誤。
Electron 無(wú)法從 dist 文件夾加載文件,因?yàn)樗静淮嬖凇H绻榭错?xiàng)目的文件夾,您將看到 Angular CLI 在 dist/electron-angular-demo 文件夾而不僅僅是 dist 文件夾中構(gòu)建您的應(yīng)用程序
在我們的 main.js 文件中,我們告訴 Electron index.html 在 dist 沒(méi)有子文件夾的文件夾中查找文件:

__dirname 指的是我們運(yùn)行 Electron 的當(dāng)前文件夾。
我們使用該 path.join()方法將當(dāng)前文件夾的/dist/index.html 路徑與路徑連接起來(lái)。
可以更改路徑的第二部分,/dist/electron-angular-demo/index.html 或者更好的是,更改 Angular 配置以輸出文件 dist 夾中的文件而不使用子文件夾。
打開(kāi) angular.json 文件,找到 projects → architect → build → options → outputPath 密鑰并將其值更改 dist/electron-angular-demo 為 dist:

再次執(zhí)行 npm run start:electron

該文章來(lái)源于 https://ld246.com/article/1559209582761
浙公網(wǎng)安備 33010602011771號(hào)