首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Rails + React + Webpack加载图像

Rails + React + Webpack加载图像
EN

Stack Overflow用户
提问于 2016-09-10 11:26:31
回答 1查看 2.5K关注 0票数 1

我使用rails + webpack将一个bundle.js文件编译到rails资产管道中。我在/app/assets/images中放置了一个名为"main.png“的图像。如何在捆绑的React组件中访问此图像?

我正在使用shakacode的react on rails gem。https://github.com/shakacode/react_on_rails

然后,我尝试使用webpack处理图像,它成功地处理了图像,并将图像放在bundle.js文件旁边。我在图像上还是得到了404。

我知道我已经很接近了,只是publicPath对于rails资产来说是错误的。这个当前的设置提供了一个本地主机:3000/webpack/main.png,它不能与rails一起工作。

这是我的webpack文件:

代码语言:javascript
运行
复制
const webpack = require('webpack');
const path = require('path');

const devBuild = process.env.NODE_ENV !== 'production';
const nodeEnv = devBuild ? 'development' : 'production';

config = {
  entry: [
    'es5-shim/es5-shim',
    'es5-shim/es5-sham',
    'babel-polyfill',
    './app/Register.js',
  ],

  output: {
    filename: 'webpack-bundle.js',
    path: '../app/assets/webpack',
    publicPath: '/webpack/'
  },

  resolve: {
    extensions: ['', '.js', '.jsx'],
    alias: {
      react: path.resolve('./node_modules/react'),
      'react-dom': path.resolve('./node_modules/react-dom'),
    },
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(nodeEnv),
      },
    }),
  ],
  module: {
    loaders: [
      {
        test: require.resolve('react'),
        loader: 'imports?shim=es5-shim/es5-shim&sham=es5-shim/es5-sham',
      },
      {
        test: /\.jsx?$/, loader: 'babel-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.(png|svg)$/i,
        loaders: [
        'file?hash=sha512&digest=hex&name=[hash].[ext]',
        'image-webpack?bypassOnDebug&interlaced=false'
        ]
      }
    ],
  },
};

module.exports = config;

if (devBuild) {
  console.log('Webpack dev build for Rails'); // eslint-disable-line no-console
  module.exports.devtool = 'eval-source-map';
} else {
  config.plugins.push(
    new webpack.optimize.DedupePlugin()
  );
  console.log('Webpack production build for Rails'); // eslint-disable-line no-console
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-10 13:01:30

正确定义加载器后,您可以使用require函数加载您的图像,例如!例如,在您的导入附近添加:

const myImg = require('./assets/methods.png');

然后,在组件的render方法中:

<img src={myImg} />

应该行得通..。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39422223

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档