mixtur / webpack-spritesmith

Webpack plugin that converts set of images into a spritesheet and SASS/LESS/Stylus mixins
498 stars 56 forks source link
spritesmith webpack-plugin

npm

A webpack plugin that converts a set of images into a spritesheet and SASS/LESS/Stylus mixins, using spritesmith and spritesheet-templates

All ideas are shamelessly taken from gulp.spritesmith.

Example

Let's say you have the following folder structure

/
|-src
| |-ico
| | |-new.png
| | |-open.png
| | |-save.png
| | ...
| |-style.styl
| ...
|-webpack.config.js

Then you need to instantiate the plugin in the webpack config like this:


//webpack.config.js
var path = require('path');

var SpritesmithPlugin = require('webpack-spritesmith');

module.exports = {
    // ...
    module: {
        rules: [
            {test: /\.styl$/, use: [
                'style-loader',
                'css-loader',
                'stylus-loader'
            ]},
            {test: /\.png$/, use: [
                'file-loader?name=i/[hash].[ext]'
            ]}
        ]
    },
    resolve: {
        modules: ["node_modules", "spritesmith-generated"]
    },
    plugins: [
        new SpritesmithPlugin({
            src: {
                cwd: path.resolve(__dirname, 'src/ico'),
                glob: '*.png'
            },
            target: {
                image: path.resolve(__dirname, 'src/spritesmith-generated/sprite.png'),
                css: path.resolve(__dirname, 'src/spritesmith-generated/sprite.styl')
            },
            apiOptions: {
                cssImageRef: "~sprite.png"
            }
        })
    ]
    // ...
};

And then just use it


//style.styl
@import '~sprite.styl'

.close-button
    sprite($close)
.open-button
    sprite($open)

There are a few things to notice in config

So the way generated image is accessed from the generated API now must be specified manually.

Config

This scary readme file is a cry for help. If someone can improve it please do. Also the config itself is terrible, it could also use some improvement. I welcome any reasonable suggestions. Thank you.