【问题标题】:React/Electron not loading static files located in public directoryReact/Electron 不加载位于公共目录中的静态文件
【发布时间】:2020-11-01 01:36:54
【问题描述】:

我已经构建了一个在 Chrome 上运行良好的 React 应用程序。现在我想把它转换成一个电子应用程序。位于/public目录下的资产(图片、图标、JSON文件)无法在电子应用中加载。
加载这些文件时浏览器控制台显示错误:
Failed to load resource: net::ERR_FILE_NOT_FOUND.
当我将公共目录中的资产图片直接插入到生成的 index.html 文件中时,例如

<img src="pic.png" alt=" pic"/>

它可以工作,但是从 react 组件中以相同的方式加载它是行不通的。资产文件正在从根目录加载(例如 file://pic.png)

这是项目结构:

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"
        }
      ]
    }
  }

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()
}

提前感谢您的帮助!

【问题讨论】:

标签: reactjs electron


【解决方案1】:

事实证明,Electron 不使用 React 的 /public 目录。所以我将所需的资产移动到 /src/assets 并直接将它们导入到组件类中。示例:

import logo from "../assets/logo.png";

class MyComponent extends React.Component {
    render() {
        <img src={logo} alt="my_logo"/>
    }
}

我还在 index.html 文件的标题中添加了&lt;base href="./"/&gt;

【讨论】:

    【解决方案2】:

    我有这个例子,你用“../”为路径收费这个例子如果你可以输入路径不需要包含“..”我希望你能解决

    import { ipcMain, dialog } from 'electron'
    import isImage from 'is-image'
    import filesize from 'filesize'
    import fs from 'fs'
    import path from 'path'
    
    function setMainIpc (win) {
      ipcMain.on('open-directory', (event) => {
        dialog.showOpenDialog(win, {
          title: 'Select new location',
          buttonLabel: 'open dir',
          properties: ['openDirectory']
        },
        (dir) => {
          if (dir) {
            loadImages(event, dir[0])
          }
        })
      })
    
      ipcMain.on('load-directory', (event, dir) => {
        loadImages(event, dir)
      })
    
      ipcMain.on('open-save-dialog', (event, ext) => {
        dialog.showSaveDialog(win, {
          title: 'save image modify',
          buttonLabel: 'save imagen',
          filters: [{name: 'Images', extensions: [ext.substr(1)]}]
        }, (file) => {
          if (file) {
            event.sender.send('save-image', file)
          }
        })
      })
    
      ipcMain.on('show-dialog', (event, info) => {
        dialog.showMessageBox(win, {
          type: info.type,
          title: info.title,
          message: info.message
        })
      })
    }
    
    function loadImages (event, dir) {
      const images = []
    
      fs.readdir(dir, (err, files) => {
        if (err) throw err
    
        for (var i = 0, length1 = files.length; i < length1; i++) {
          if (isImage(files[i])) {
            let imageFile = path.join(dir, files[i])
            let stats = fs.statSync(imageFile)
            let size = filesize(stats.size, {round: 0})
            images.push({filename: files[i], src: `plp://${imageFile}`, size: size})
          }
        }
    
        event.sender.send('load-images', dir, images)
      })
    }
    
    module.exports = setMainIpc

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-12
      • 2010-10-19
      • 2021-09-21
      • 2019-10-09
      相关资源
      最近更新 更多