【问题标题】:Webpack SCSS Image URL Links Broken on Nested RoutesWebpack SCSS 图像 URL 链接在嵌套路由上断开
【发布时间】:2016-12-25 17:53:55
【问题描述】:

这是我的目录结构:

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

还有:

// 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']
  }
};

还有:

/* 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;
}

加载单级路由时,我的图片链接正常工作。

例如,在/search,图像链接呈现为url(images/img-75fa3d.png) 并且有效。

但是,如果我使用嵌套路由(通过 React Router),例如/properties/1 图片链接相同,无法找到正确的图片位置,因为它是相对链接:url(images/img-75fa3d.png)

此示例中的图像是logo-b-green.png

编辑:

我将publicPath 添加到output 部分并且它起作用了,现在网址进入了根目录。有人可以确认这是处理此问题的正确方法吗?

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

【问题讨论】:

  • 我打算建议设置publicPath,所以是的。 AFAIK,它用于为资源添加 URL 前缀。

标签: sass webpack react-router babeljs sass-loader


【解决方案1】:

我将publicPath 添加到output 部分并且它有效,现在网址进入了根目录。

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

【讨论】:

    猜你喜欢
    • 2017-10-22
    • 2017-10-30
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    相关资源
    最近更新 更多