首页 文章

使用webpack文件加载器访问嵌套的react-routes中的资源

提问于
浏览
1

我最近使用reactHistory中的react-router切换到了路由器历史记录 . 但是有一个问题 . 每次我访问嵌套路由并尝试刷新页面时,都无法找到公共资源,例如我的徽标,因为它使用嵌套路由的第一部分作为资源的根 .

在我的index.js中,我需要如下图像:

require('./images/logo-icon.png');

我在导航栏组件中使用了一个徽标,如下所示:

<Link to="/" className="gc-padding-none">
        <img alt="Get Cooked" className="gc-logo-default" src="images/logo-icon.png" />
      </Link>

这是我的路线:

<Route path="/" component={NavigationBar}>
    <IndexRoute component={Home} />
    <Route path="/chefs" component={ProfileList} />
    <Route exact path="register" component={Register} redirect />
      <Route path="chef">
          <Route path="register" component={RegisterChef} />
      </Route>
</Route>

这是我的webpack配置:

var HtmlWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
  template: __dirname + '/client/index.html',
  filename: 'index.html',
  inject: 'body'
});

module.exports = {
  entry: [
    './client/index.js'
  ],
  output: {
    path: __dirname + '/dist',
    filename: 'index_bundle.js',
    publicPath: '/'
  },
  devServer: {
    historyApiFallback: true,
    inline: true,
    contentBase: './client',
    port: 8080,
    proxy: { '/api/**': { target: 'http://localhost:3000', secure: false } }
  },
  module: {
    loaders: [
      {test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', query: {presets: ['es2015','react'], plugins: ['transform-es2015-destructuring', 'transform-object-rest-spread']}},
        {test: /\.jpe?g$|\.gif$|\.svg$|\.png$/i, loader: 'file-loader?name=/images/[name].[ext]'},
        {test: /\.css$/, loaders: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader','resolve-url-loader']},
        {test: /\.scss$/, loaders: ['style-loader', 'css-loader','postcss-loader', 'sass-loader','resolve-url-loader']}
        ]
  },
  plugins: [HTMLWebpackPluginConfig]
};

每次我去'/'或'/ chefs'一切都很好,但是,当我访问嵌套路线,如'/ chef / register'并刷新我的浏览器时,导航栏组件中找不到徽标 .

出现以下错误:

logo-icon.png:1 GET http://localhost:8080/chef/images/logo-icon.png 404 (Not Found)

正如您所看到的,徽标正在尝试从包含我的路线'/ chef'的第一部分的位置获取 .

我尝试删除webpack中的publicPath配置,但这会影响刷新时嵌套组件的呈现 .

有关为什么会发生这种情况的任何想法?

1 回答

  • 2

    解释elmeister的评论,

    images/logo-icon.png 是一个相对路径,使其依赖于当前路径 .

    因此,来自url http://localhost:8080/chef/images/logo-icon.png 请求会导致 http://localhost:8080/chef/images/logo-icon.png 的请求 .

    /images/logo-icon.png 是一个绝对路径,确保路径始终基于站点的根,无论当前路径是什么 .

    因此,来自url http://localhost:8080/chef//images/logo-icon.png 请求将导致 http://localhost:8080/images/logo-icon.png 的请求 .

相关问题