mixtur / webpack-spritesmith

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

generating multiple sprites #19

Closed shaurabh-singh closed 7 years ago

shaurabh-singh commented 8 years ago

Hi, I am developing a SPA which have many sprites. And for each sprite I have to make a new entry in the plugin with similar configurations. Is there any way to generate multiple sprites by one entry?

For example, below is the directory structure

 images
        └── spritesource
            └── home
            │   └── example.png
            │    ─── example2.png
            └── users
                 └── user.png
src: {       cwd: path.resolve(__dirname, 'images/spritesource'),
                glob: '*.png'
       },
target: {  image: path.resolve(__dirname, 'images/sprites),
                css: path.resolve(__dirname, 'images/sprites')
       }  

expected output:

images
        └── sprites
            └── home
                └── home.png
                 ─── home.scss
            └── users
                └── users.png
                 ─── users.scss
        └── spritesource
            └── home
                └── example.png
                 ─── example2.png
            └── users
                 └── user.png

The src has the path of a parent directory which have 2 child directories. These child directories have images. The target should generate 2 sprites and 2 scss, each for the child directory.

mixtur commented 8 years ago

Exactly that way no, you can't. But you can arrange modularity for sprites with apiOptions.generateSpriteName. Check out this config. In that case you still get one scss file but variable names would be like $home__example, $home__example2. Is that good enough?

mixtur commented 7 years ago

I don't think what you asking for is possible internally in plugin. General case would be too general) Though you can still do something to avoid code duplication in webpack config.

For example in your case, you can use for example glob to get directory structure. Then generate as many plugin instances as you like.

Or another approach. Turn that big config to one-liner with some helper function. Like

const makeSprite = (path) => new SpritesmithPlugin({
  src: {
    cwd: path.resolve(__dirname, 'images/spritesource', path),
    glob: '*.png'
  },
  target: {
    image: path.resolve(__dirname, 'images/sprites', path),
    css: path.resolve(__dirname, 'images/sprites', path)
  },
  ...
});

//... then in webpack.config.js

plugins: [
  makeSprite('home'),
  makeSprite('users')
]