Unable to resolve absolute url() paths for background images in CSS with Webpack

后端 未结 2 643
梦谈多话
梦谈多话 2021-02-09 08:52

I have the following Webpack config (roughly, it has been simplified for this post):

const rootPublic = path.resolve(\'./public\');
const LOCAL_IDENT_NAME = \'lo         


        
相关标签:
2条回答
  • 2021-02-09 09:42

    One possible solution that I could come up with was the following:

    Use resolve-url-loader (immediately after sass-loader):

    style!${CSS_LOADER}!autoprefixer!resolve-url!${SASS_LOADER}
    

    Then, define a resolve.alias for static images:

    resolve: {
      alias: {
        images: path.join(__dirname, 'public/images')
      }
    }
    

    And then in the CSS, you can point to the images like so:

    :local .SomeClass {
      background: url('images/bg.png');
    }
    

    Depending on your URL structure, you may also need to tweak the url-loader name param:

    {
      test: /\.(jpe?g|png|gif|svg)$/,
      loader: 'url-loader?limit=10000&name=images/[name].[ext]'
    }
    

    So I don't know if there's a cleaner way to solve this issue, but that's the best I could come up with so far. I'd welcome any feedback or alternatives.

    Thanks!

    UPDATE 6/30/2016

    There's a couple PR's out that would address this issue, but the maintainer prefers the solution to be in the CSS AST rather than in the CSS loader...

    https://github.com/webpack/style-loader/pull/124 https://github.com/webpack/style-loader/pull/96

    Here's hoping a real fix happens soon...

    0 讨论(0)
  • 2021-02-09 09:42

    With webpack 2:

    In your .scss files use ~ before the path.

    .yourClass {
          background: url('~img/wallpaper.png');
    }
    

    Make use of the resolve root from webpack, add this to your webpack.config.js:

    resolve: {
            modules: [
                path.resolve(root),
                'node_modules'
            ]
        },
    

    It should work also for the @import, eg @import "~otherfile.scss"

    0 讨论(0)
提交回复
热议问题