webpack+react 本地调试时图片无法加载

我的webpack配置

// ...
entry: {
    index: './src/root.js'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/'
  }
// ...
{
      test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
      loader: 'url-loader',
      options: {
        limit: 10000,
        name: 'img/[name].[hash:7].[ext]'
      }
    }

html 使用相对路径

<img src='../../static/imgs/logo.png' alt='icon'></img>

服务器代码

// ...
var app = express()
var compiler = webpack(config)

app.use(require('webpack-dev-middleware')(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath
}))

app.use(require('webpack-hot-middleware')(compiler))


app.listen(3000, function(err) {
  if (err) {
    console.log(err)
    return
  }
  console.log('Listening at http://localhost:3000')
})

问题是图片无法加载,请问一下我图片引用的路径应该怎么写

我html改成这种写法:

const logo = require('../../static/imgs/logo.png')
<img src={logo} alt='icon'></img>

就提示缺少file-loader,这样的原因又是为什么,和上面的引用方式那种比较好

阅读 4.9k
1 个回答

使用第二种方式加载,在webpack中加上file-loader的配置就可以了,网上一搜就会。
用第一种方式的话要写绝对路径,相对路径webpack会认为是一个普通字符串,不做处理,在编译后就无法找到图片的地址了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题