2

I'm using webpack with React on Rails and have some react components that need to reference images.

The problem I'm having is trying to get Rails to access the images. Rails has its images served from its usual app/assets/images directory which is accessed via the url /assets

If however I have a react component and an image in an image directory:

component.js

images/image.jpg

+--component.js +--images/image.jpg

If I try to reference the image by its relative path within component.js eg When I load the page in rails the page tries to access the url http://localhost:3000/home/images/image.jpg and not the url that rails expects the assets to be http://localhost:3000/assets/images/image.jpg

Does anyone know how to correct this?

This is my webpack.config

const webpack = require('webpack')
const path = require('path')

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

const config = {
  entry: [
    'whatwg-fetch',
    'es5-shim/es5-shim',
    'es5-shim/es5-sham',
    'babel-polyfill',
    './app/bundles/index.js'
  ],

  output: {
    filename: 'webpack-bundle.js',
    path: '../app/assets/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: /\.(jpe?g|png|gif|svg|ico)$/, loader: 'file-loader'
      },
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      }
    ]
  }
}

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
}
Riina
  • 530
  • 1
  • 7
  • 19
  • Possible duplicate of [Webpack outputs wrong path for images](http://stackoverflow.com/questions/33243399/webpack-outputs-wrong-path-for-images) – Peter Feb 15 '17 at 22:37

0 Answers0