【问题标题】:Webpack & React. Loaded image can't resolve path 404Webpack 和反应。加载的图像无法解析路径 404
【发布时间】:2017-07-24 15:52:10
【问题描述】:

在这种情况下,我正在尝试设置某种高阶组件并进一步为其实现“动态”图像加载。您能否解释一下为了引用组件内部而做错了什么。

反应组件

class Slide extends Component {
  constructor(props) {
    super(props)
  }

  render () {

    let imageLeft = {
     backgroundImage: 'url(./assets/introleft.png)'
    }

    return (
      <div className={styles.someStyles}>
        <div className={styles.someStyles} style={imageLeft} >&nbsp;</div>
      </div>
    )
  }

}

... state

export default connect(mapStateToProps)(Slide);

项目结构

Webpack 配置

const path = require('path'),
      webpack = require('webpack'),
      HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: [
    'react-hot-loader/patch', 
    'webpack-dev-server/client?http://localhost:8080', 
    'webpack/hot/only-dev-server',  
    './index.js'
  ],
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'build'), 
    publicPath: '/'
  },  
  context: path.resolve(__dirname, 'logic'), 
  devtool: 'inline-source-map',    
  devServer: {
    hot: true, 
    contentBase: path.resolve(__dirname, 'build'),
    publicPath: '/'
  },

  module: {
    rules: [
      {
        test: /\.js$/,
        use: [
          'babel-loader',
        ],
        exclude: /node_modules/
      },
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader?modules',
          'postcss-loader',
        ],
      },{
        test: /\.png$/,
        use: { loader: 'url-loader', options: { limit: 15000 } },
      },
      {
        test: /\.svg$/,
        use: {
          loader: 'svg-url-loader',
          options: {}
      }
    ],
  },

  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
    new HtmlWebpackPlugin({
      template: './index.template.html'
    })<script> tag
  ],
};

P.S: 项目没有node.js 服务器,只有wepback-dev。所以 react-router 使用哈希历史 /#,如果它以某种方式影响了 webpack publicPath 属性,则使用 hasher。

【问题讨论】:

    标签: reactjs webpack webpack-2


    【解决方案1】:

    当您使用backgroundImage: 'url(./assets/introleft.png)' 时,它将按原样插入(它只是一个字符串),因此您的url-loader 不会应用于它。相反,您应该导入图像:

    import introleft from './assets/introleft.png';
    

    Webpack 将应用 url-loader,如果尺寸太大,您将返回数据 URL 或提取图像的 URL。您现在需要做的就是将该 URL 放入您的backgroundImage

    backgroundImage: `url(${introleft})`
    

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 2017-12-15
      • 2018-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-23
      相关资源
      最近更新 更多