无法将Angular应用作为Electron应用加载的问题求助
Angular + Electron 资源路径错误:请求指向磁盘根目录而非构建目录
开发Electron应用时,Angular是推荐方案(其次是Vue),因此将Angular应用作为Electron加载本应无特殊问题,只需使用单独的tsconfig.electron.json并正确配置package.json中的main入口。
配置详情
package.json 相关配置
{ "main": "./out-tsc/electron-main/electron-main.js", "name": "angular-electron1", "scripts": { "build:angular": "ng build", "build:electron-main": "tsc -p tsconfig.electron.json", "build:all": "ng build && tsc -p tsconfig.electron.json", "electron:start": "npm run build:angular && npm run build:electron-main && npx cross-env NODE_ENV=development electron .", "ng": "ng", "start": "ng serve", "build": "ng build", "watch": "ng build --watch --configuration development", "test": "ng test" }, }
tsconfig.electron.json 配置
{ "extends": "./tsconfig.json", "compilerOptions": { "module": "CommonJS", "outDir": "./out-tsc/electron-main" }, "include": ["src/electron/preload.ts", "src/electron-main.ts"], "exclude": ["src/angular-main.ts", "src/**/*.spec.ts", "src/app/**/*.ts"] }
angular.json 配置片段
"options": { "baseHref": "/" , }
Angular构建产物信息
构建产物输出到 E:\Angular\AngularElectron1\AngularElectron1\dist\angular-electron1\browser 目录,单独运行Angular应用完全正常,产物文件包括:
- favicon.ico
- index.html
- main-KPJ5OKOH.js
- polyfills-FFHMD2TL.js
- styles-5INURTSO.css
Content-Security-Policy 配置
在HTML中添加了如下安全配置:
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self';">
Electron 主进程代码
使用最基础的启动代码(未使用preload.js)加载Angular应用:
import { app, BrowserWindow } from 'electron'; import * as path from 'path'; let win: BrowserWindow | null; const createWindow = () => { win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true, contextIsolation: false, }, }); const indexPath = path.resolve(process.cwd(), 'dist', 'angular-electron1', 'browser', 'index.html'); win.loadFile(indexPath); win.on('closed', () => { win = null; }); }; app.on('ready', createWindow); app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); }); app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); });
报错信息
运行时资源请求路径指向磁盘E:\根目录而非Angular构建目录,报错如下:
GET file:///E:/styles-5INURTSO.css net::ERR_FILE_NOT_FOUND GET file:///E:/polyfills-FFHMD2TL.js net::ERR_FILE_NOT_FOUND GET file:///E:/main-KPJ5OKOH.js net::ERR_FILE_NOT_FOUND
疑问
应用根目录应为 E:\Angular\AngularElectron1\AngularElectron1\dist\angular-electron1\browser,为何Electron会将磁盘根目录识别为应用根目录?
内容的提问来源于stack exchange,提问作者Alex161
相关产品推荐
相关产品推荐

