3

我正在使用 Electron + React + Webpack 模式为 Mac OS 构建桌面应用程序。当我将 Electron 桌面应用程序构建为生产版本时,我想在设置文件(Test.app 和 Test.dmg)中插入一些图像文件并使用如下图像:

let Logo = process.resourcesPath + '/logo.png';

class Loading extends Component {
  render() {
    return (
        <div className={styles.container}>
          <img className={styles.logo} src={Logo} />
          ...
       </div>
      );
  }
}

但是这个应用程序无法获取图像,因为当我运行“npm run package”命令并为 Mac OS 构建 Test.app 时,logo.png 文件没有包含在 Test.app/Content/Resources/ 目录中。

在这里,问题如下:

GET file:///Applications/Test.app/Contents/Resources/logo.png net::ERR_FILE_NOT_FOUND

我想将此图像文件插入我的 Mac OS 的 Test.app 包中。

请帮助我如何将一些图像文件插入到 Mac OS 桌面应用程序的 Test.app 包中。


webpack.config.base.js

import path from 'path';
import webpack from 'webpack';
import { dependencies as externals } from './app/package.json';

export default {
  externals: Object.keys(externals || {}),

  module: {
    rules: [{
      test: /\.jsx?$/,
      exclude: /node_modules/,
      use: {
        loader: 'babel-loader',
        options: {
          cacheDirectory: true
        }
      }
    }]
  },

  output: {
    path: path.join(__dirname, 'app'),
    filename: 'bundle.js',
    // https://github.com/webpack/webpack/issues/1114
    libraryTarget: 'commonjs2'
  },

  resolve: {
    extensions: ['.js', '.jsx', '.json'],
    modules: [
      path.join(__dirname, 'app'),
      'node_modules',
    ],
  },

  plugins: [
    new webpack.NamedModulesPlugin(),
  ],
};

webpack.config.production.js

import path from 'path';
import webpack from 'webpack';
import validate from 'webpack-validator';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import merge from 'webpack-merge';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import BabiliPlugin from 'babili-webpack-plugin';
import baseConfig from './webpack.config.base';

export default validate(merge(baseConfig, {
  devtool: 'cheap-module-source-map',

  entry: './app/index',

  output: {
    publicPath: '../dist/'
  },

  module: {
    loaders: [
      // Extract all .global.css to style.css as is
      {
        test: /\.global\.css$/,
        loader: ExtractTextPlugin.extract(
          'style-loader',
          'css-loader'
        )
      },

      // Pipe other styles through css modules and append to style.css
      {
        test: /^((?!\.global).)*\.css$/,
        loader: ExtractTextPlugin.extract(
          'style-loader',
          'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
        )
      },

      // Fonts
      { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?name=fonts/[hash].[ext]&limit=50000&mimetype=application/font-woff' },
      { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?name=fonts/[hash].[ext]&limit=50000&mimetype=application/font-woff' },
      { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?name=fonts/[hash].[ext]' },
      { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?name=fonts/[hash].[ext]' },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?name=fonts/[hash].[ext]' },

      // Images
      {
        test: /\.(?:ico|gif|png|jpg|jpeg|webp)$/,
        loader: 'url-loader'
      }
    ]
  },

  plugins: [
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production')
    }),
    new BabiliPlugin({
      // Disable deadcode until https://github.com/babel/babili/issues/385 fixed
      deadcode: false,
    }),
    new webpack.optimize.UglifyJsPlugin({
      compressor: {
        screw_ie8: true,
        warnings: false
      }
    }),
    new ExtractTextPlugin('style.css', { allChunks: true }),
    new HtmlWebpackPlugin({
      filename: 'app.html',
      template: 'app/app.html',
      inject: false
    })
  ],

  target: 'electron-renderer'
}));

webpack.config.electron.js

/**
 * Build config for electron 'Main Process' file
 */

import webpack from 'webpack';
import validate from 'webpack-validator';
import merge from 'webpack-merge';
import BabiliPlugin from 'babili-webpack-plugin';
import baseConfig from './webpack.config.base';

export default validate(merge(baseConfig, {
  devtool: 'source-map',

  entry: ['babel-polyfill', './main.development'],

  // 'main.js' in root
  output: {
    path: __dirname,
    filename: './main.js'
  },

  plugins: [
      deadcode: false,
    }),

    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production')
      }
    })
  ],

  target: 'electron-main',

  node: {
    __dirname: false,
    __filename: false
  }
}));

package.json 的脚本部分

  "scripts": {
    "test": "cross-env NODE_ENV=test BABEL_DISABLE_CACHE=1 node --trace-warnings ./test/runTests.js",
    "test-all": "npm run lint && npm run flow && npm run test && npm run build && npm run test-e2e",
    "test-watch": "npm test -- --watch",
    "test-e2e": "cross-env NODE_ENV=test BABEL_DISABLE_CACHE=1 node --trace-warnings ./test/runTests.js e2e",
    "lint": "eslint --cache --format=node_modules/eslint-formatter-pretty .",
    "lint-fix": "npm run lint -- --fix",
    "lint-styles": "stylelint app/*.css app/components/*.css --syntax scss",
    "hot-updates-server": "cross-env NODE_ENV=development node --trace-warnings -r babel-register ./node_modules/webpack-dev-server/bin/webpack-dev-server --config webpack.config.renderer.dev.js",
    "build": "concurrently \"npm run copy-images\" \"npm run build-main\" \"npm run build-renderer\"",
    "build-dll": "cross-env NODE_ENV=development node --trace-warnings -r babel-register ./node_modules/webpack/bin/webpack --config webpack.config.renderer.dev.dll.js --progress --profile --colors",
    "build-main": "cross-env NODE_ENV=production node --trace-warnings -r babel-register ./node_modules/webpack/bin/webpack --config webpack.config.main.prod.js --progress --profile --colors",
    "build-renderer": "cross-env NODE_ENV=production node --trace-warnings -r babel-register ./node_modules/webpack/bin/webpack --config webpack.config.renderer.prod.js --progress --profile --colors",
    "start": "cross-env NODE_ENV=production electron ./app/",
    "prestart": "npm run build",
    "flow": "flow",
    "flow-typed": "rm -rf flow-typed && flow-typed install --overwrite || true",
    "start-hot-renderer": "cross-env HOT=1 NODE_ENV=development electron -r babel-register -r babel-polyfill ./app/main.development",
    "postinstall": "concurrently \"npm run flow-typed\" \"npm run build-dll\" \"install-app-deps\" \"node node_modules/fbjs-scripts/node/check-dev-engines.js package.json\"",
    "dev": "cross-env START_HOT=1 npm run hot-updates-server",
    "package": "npm run build && build --publish never",
    "package-win": "npm run build && build --win --x64",
    "package-linux": "npm run build && build --linux",
    "package-all": "npm run build && build -mwl",
    "cleanup": "mop -v",
    "copy-images": "cp -Rf app/shared/images/ app/dist/images/"
  },
  "browserslist": "electron 1.4",
  "build": {
    "productName": "Test",
    "appId": "org.Test",
    "files": [
      "dist/",
      "node_modules/",
      "app.html",
      "main.js",
      "main.js.map",
      "package.json"
    ],
    "dmg": {
      "contents": [
        {
          "x": 130,
          "y": 220
        },
        {
          "x": 410,
          "y": 220,
          "type": "link",
          "path": "/Applications"
        }
      ]
    },
    "win": {
      "target": [
        "nsis"
      ]
    },
    "linux": {
      "target": [
        "deb",
        "AppImage"
      ]
    },
    "directories": {
      "buildResources": "resources",
      "output": "release"
    }
  },
4

2 回答 2

0

在 electron 和 react.js 中使用 img 的简单方法

将您的 imgs 存储在一个文件夹中并像这样导入它

import image_src from './../img/your_image.png';

// Use it inline like so (in React)
class YourImage extends React.Component {
 render(){
    return (
      <img src={image_src} />    
    )
 }

}

于 2021-11-30T05:00:49.190 回答
0

安装电子应用程序后,它将所有源代码和资源文件放入一个.asar包中。所以要插入任何图像,你必须使用应用程序之外的目录。通常这个目录可以是一个 Document 文件夹。

const { remote } = require('electron');
let tempFolder =path.join( remote.app.getPath("documents"), 'AppFiles');

使用tempFolder目录保存图像。

于 2020-09-16T07:43:29.430 回答