Webpack SCSS Image URL Links Broken on Nested Routes

谁说我不能喝 提交于 2019-12-13 13:02:04

问题


Here is my directory structure:

- public
- src
  - app.js
  - assets
    - images
      - logo-b-green.png 
    - stylesheets
      - nav.scss

And:

// webpack.config.js

module.exports = {
  entry: './src/app.js',
  output: {
    path: './public',
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        test: /.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      },
      {
        test: /\.scss$/,
        loaders: ['style', 'css', 'sass']
      },
      {
          test: /\.(eot|svg|ttf|woff|woff2)$/,
          loader: 'file?name=fonts/[name].[ext]'
      },
      {
        test: /\.(png|jpg|gif)$/,
        loader: "file-loader?name=images/img-[hash:6].[ext]"
      }
    ]
  },
  resolve: {
    extensions: ['', '.js', '.json']
  }
};

And:

/* nav.scss */

#nav-logo {
  height: 26px;
  width: 26px;
  background-size: 100%;
  background-image: url('../images/logo-b-green.png');
  float: left;
  margin: 16px 0 0 23px;
}

When loading single level routes my image links work correctly.

For example at /search the image link is rendered as url(images/img-75fa3d.png) and works.

However, if I go to a nested route (via React Router), e.g. /properties/1 the image link is the same and cannot find the correct image location as it's a relative link: url(images/img-75fa3d.png).

The image from this example is logo-b-green.png.

EDIT:

I added the publicPath to the output section and it worked, now the urls go the root. Can someone confirm that this is the correct way to handle this?

output: {
 path: './public',
 filename: 'bundle.js',
 publicPath: '/'
}, ...

回答1:


I added the publicPath to the output section and it worked, now the urls go the root.

output: {
 path: './public',
 filename: 'bundle.js',
 publicPath: '/'
}, ...


来源:https://stackoverflow.com/questions/39024319/webpack-scss-image-url-links-broken-on-nested-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!