tonghae
tonghae

Reputation: 115

Resolving relative urls in nested style files with postcss & scss

I'm using postcss with scss synthax to organize styles in project. The simplified structure listed below:

client
  media
    images
      image.png
  styles
    index.scss
    components
      component1.scss

Entry point for Webpack loaders is client/styles/index.scss.

If I define some style with url() statement with relative path to image.png - like url('../media/images/image.png') (for example - in background-image property) in index.scss it will be resolved fine.

But if I do same thing in nested style file - styles/components/component1.scss - url('../../media/images/image.png') which is imported by index.scss — Webpack will throw an error:

Module not found: Error: Can't resolve '../../media/images/image.png' in '/Users/anubis/Projects/Jackal/client/styles'

Seems that loader treat relative urls in all nested files with entry style file path. How to change this behavior?

{
  test: /\.scss$/,
  use: [
    { loader: 'style-loader' },
    {
      loader: 'css-loader',
      options: {
        importLoaders: 1,
        sourceMap: true,
        minimize: true
      }
    },
    {
      loader: 'postcss-loader',
      options: {
        ident: 'postcss',
        parser: scssParser,
        sourceMap: true,
        plugins: () => [
          require('precss')({
            import: {
              resolve: styleFileResolver
            }
          }),
          require('postcss-font-magician')({
            hosted: ['./client/media/fonts/OpenSans']
          }),
          require('postcss-short')(),
          require('postcss-cssnext')(),
          require('postcss-utilities')()
        ]
      }
    }
  ]
}

Upvotes: 1

Views: 1867

Answers (1)

Roman Usherenko
Roman Usherenko

Reputation: 5639

You're missing a resolve-url-loader. You can try adding it between css and postcss loaders

Upvotes: 1

Related Questions