I've built a React app that works fine on Chrome. Now I wanted to convert it into an Electron app. The assets located in the /public
directory (pictures, icons, JSON files) cannot be loaded in the electron app.
The browser console displays errors while loading these files:
Failed to load resource: net::ERR_FILE_NOT_FOUND
.
When I insert an asset picture from the public directory directly in the generated index.html file like
<img src="pic.png" alt=" pic"/>
it works, but loading it the same way from react components doesn't work. The asset files are being loaded from the root (e.g. file://pic.png)
Here is the project structure:
package.json:
"homepage": "./",
"main": "src/electron-starter.js",
"build": {
"appId": "com.myapp",
"productName": "App",
"files": [
"build/**/*",
"src/electron-starter.js"
],
"directories": {
"buildResources": "public"
},
"win": {
"target": "NSIS"
},
"linux": {
"target": [
"AppImage",
"deb"
],
"category": "Audio"
},
"dmg": {
"contents": [
{
"x": 110,
"y": 150
},
{
"x": 240,
"y": 150,
"type": "link",
"path": "/Applications"
}
]
}
}
createWindow function inside electron-starter.js:
function createWindow () {
const mainWindow = new BrowserWindow({
width: 1200,
height: 700,
webPreferences: {
nodeIntegration: true
}
})
if (process.env.ELECTRON_START_URL) {
mainWindow.loadURL(process.env.ELECTRON_START_URL);
} else {
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, '../build/index.html'),
protocol: 'file',
slashes: true
}))
}
mainWindow.webContents.openDevTools()
}
Thank's in advance for your help!