Angular 19转Electron应用后build/assets目录图片加载404问题求助
Angular 19转Electron应用后build/assets目录图片加载404问题求助
各位大佬好!最近我在把Angular 19项目打包成Electron生产应用时遇到了超级头疼的问题——build目录下assets文件夹里的图片全部报404错误,折腾了好几种方法都没完全解决,来这里求大家支支招!
问题详情
我的项目是monorepo里的其中一个,经理要求生产环境的build文件夹命名是固定的。本地单独打开build文件夹里的HTML文件时,图片加载完全正常,但在Electron应用里,assets下的图片路径被错误解析成了file:///C:/assets/images/homepage/folder-disabled.svg,而正确的路径应该是file:///C:/desktop/project/project/assets/images/homepage/folder-disabled.svg,直接跳过了项目所在的目录,导致资源找不到。
我已经尝试过的方法(都没解决问题)
- 自定义Electron协议:写了个
my-protocol来转成file协议,但资源还是没正确加载app.whenReady().then(() => { protocol.handle('my-protocol', async (request) => { const filePath = request.url.replace(`my-protocol://`, 'file://'); return net.fetch(filePath); }); createWindow(); }); - 调整
index.html的<base href>:只有设为./的时候应用能跑起来,但图片还是404;设为/的话应用直接打不开 - 修改Angular的asset打包配置:添加了glob规则指定assets的输入输出,但路径问题依旧
{ "glob": "**/*", "input": "public" }, { "glob": "**/*", "input": "src/assets", "output": "/assets" } - 关闭Electron的webSecurity:在webPreferences里设
webSecurity: false,还是没效果
最小复现代码
electron.js
const { app, BrowserWindow, protocol } = require('electron') const url = require('url'); const path = require('path'); let mainWindow; function createWindow() { mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true // 启用渲染进程的Node.js集成 } }); // 加载Angular应用的index.html mainWindow.loadURL( url.format({ pathname: path.join(__dirname, `./dist-avprod/index.html`), // 对应我的build目录 protocol: 'file:', slashes: true }) ); // 打开开发者工具(可选) // mainWindow.webContents.openDevTools(); mainWindow.on('closed', () => { mainWindow = null; }); } app.whenReady().then(() => { protocol.interceptFileProtocol('file', (req, callback) => { const url = req.url.substr(7); // 去掉'file://'前缀 let normalizedPath = url; if (url.startsWith('/assets')) { // 尝试拼接项目路径,但没生效 normalizedPath = path.join(__dirname, 'dist-avprod', url); } callback({ path: normalizedPath }); }); createWindow(); }); app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } }); app.on('activate', () => { if (mainWindow === null) { createWindow(); } });
angular.json关键配置
"architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { "baseHref": "./", "outputPath": "dist/actianone-ui-console", "index": "src/index.html", "main": "src/main.ts", "polyfills": "src/polyfills.ts", "tsConfig": "src/tsconfig.app.json", "assets": [ "src/favicon.ico", "./src/assets/images", "src/assets/actian", "src/assets/config" ], } } }
求各位大神指点!到底哪里出问题了?有没有更可靠的方法能让Electron正确识别assets的路径?
内容来源于stack exchange
相关产品推荐
相关产品推荐

