我已经构建了一个在 Chrome 上运行良好的 React 应用程序。现在我想把它转换成一个 Electron 应用程序。 Assets 位于 /public
Electron 应用程序中无法加载目录(图片、图标、JSON 文件)。
浏览器控制台在加载这些文件时显示错误:Failed to load resource: net::ERR_FILE_NOT_FOUND
.
当我将公共(public)目录中的 Assets 图片直接插入到生成的 index.html 文件中时,例如
<img src="pic.png" alt=" pic"/>
它可以工作,但是从 react 组件以相同的方式加载它不起作用。 Assets 文件正在从根目录加载(例如 file://pic.png)这是项目结构:
包.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"
}
]
}
}
electron-starter.js 中的 createWindow 函数: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()
}
在此先感谢您的帮助!
最佳答案
事实证明 Electron 没有使用 React 的 /公共(public)目录。所以我将所需的 Assets 移到 /src/ Assets 并将它们直接导入到组件类中。例子:
import logo from "../assets/logo.png";
class MyComponent extends React.Component {
render() {
<img src={logo} alt="my_logo"/>
}
}
我还添加了 <base href="./"/>
到 index.html 文件的标题。
关于reactjs - React/Electron 不加载位于公共(public)目录中的静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62849060/