VoY
VoY

Reputation: 5699

How to use spriting with Webpack and Sass?

I am moving my build system from Grunt with custom tasks to Webpack. As for JavaScript modules it works great, but I'm not so sure what to do with my Sass stylesheets.

I have dependencies on Sass files in my AMD modules, which Webpack can read and generate bundle.css from. But I would ideally like to have my build pipeline generate sprites using spritesmith, then copy the images to the build dir and use the Sass mixins to generate correct CSS rules.

I have researched this a lot both on SO and Google, but haven't found anyone doing similar scenario. Should I use solely webpack? Or should I maybe have separate Grunt task watching the images, generating sprites and then run Webpack over that?

Upvotes: 6

Views: 5631

Answers (2)

mixture
mixture

Reputation: 127

I had similar problem, the only solution I've been able to come up with was to write my own plugin.

Upvotes: 5

w00t
w00t

Reputation: 18281

I have a similar problem, I have a directory full of png files that I need to convert to CSS so that a div with the correct class name will load the image. I would like to use url-loader so that small files are inlined.

The problem is of course that you can't specify a directory as something a loader should load, only existing files.

My solution is to create a custom loader in the png dir and give it itself as input, so it can glob the files in its own dir and export the CSS with all the require statements for the png files.

This is the webpack entry for it:

'!!style!css!./resources/images/images-as-css-loader.coffee!./resources/images/images-as-css-loader'

The loader code (coffeescript but you get the idea):

glob = require 'glob'
path = require 'path'
sizeOf = require 'image-size'

module.exports = (dummy) ->
  this.cacheable true

  dir = path.dirname this.resourcePath
  entries = for file in glob.sync "#{dir}/*.png"
    @addDependency file
    className = (path.basename file, '.png')
    imgDim = sizeOf file
    """
      .#{className} {
        width: #{imgDim.width}px;
        height: #{imgDim.height}px;
        background-repeat: no-repeat;
        background-image: url('~!!url?limit=1024!#{file}');
      }

    """

  # Return CSS text
  return entries.join ''

You can then use the webpack text extract plugin to move the CSS to a file, which I do for the production build. For dev I just let the style loader inject it.

Upvotes: 5

Related Questions