electron打包 静态资源访问路径
时间: 2023-09-03 20:10:46 浏览: 92
在 electron 打包后,静态资源访问路径可以通过以下代码实现:
```javascript
const path = require('path');
const { app, BrowserWindow } = require('electron');
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
// 加载 index.html 文件
mainWindow.loadFile('index.html');
// 设置静态资源访问路径
mainWindow.webContents.on('did-finish-load', () => {
mainWindow.webContents.executeJavaScript(`
const path = require('path');
const __dirname = '${__dirname}';
const staticPath = path.join(__dirname, 'static');
document.getElementById('root').setAttribute('src', staticPath);
`);
});
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();
}
});
```
其中,`__dirname` 为打包后的应用程序所在路径,`static` 为静态资源所在路径,`document.getElementById('root')` 为需要设置静态资源的元素。