Code Monkey home page Code Monkey logo

postcss-sprites's Introduction

postcss-sprites Build Status npm version

PostCSS plugin that generates spritesheets from your stylesheets.

/* Input */
.comment { background: url(images/sprite/ico-comment.png) no-repeat 0 0; }
.bubble { background: url(images/sprite/ico-bubble.png) no-repeat 0 0; }

/* ---------------- */

/* Output */
.comment { background-image: url(images/sprite.png); background-position: 0 0; }
.bubble { background-image: url(images/sprite.png); background-position: 0 -50px; }

Usage

var fs = require('fs');
var postcss = require('postcss');
var sprites = require('postcss-sprites');

var css = fs.readFileSync('./css/style.css', 'utf8');
var opts = {
	stylesheetPath: './dist',
	spritePath: './dist/images/'
};

postcss([sprites(opts)])
	.process(css, {
		from: './css/style.css',
		to: './dist/style.css'
	})
	.then(function(result) {
		fs.writeFileSync('./dist/style.css', result.css);
	});

See PostCSS docs for examples for your environment.


Options

stylesheetPath

Relative path to the folder that will keep your output stylesheet(s). If it's null the path of CSS file will be used.

  • Default: null
  • Required: false
spritePath

Relative path to the folder that will keep your output spritesheet(s).

  • Default: ./
  • Required: true
basePath

Your base path that will be used for images with absolute CSS urls.

  • Default: ./
  • Required: false
relativeTo

Indicates whether the url should be relative against current CSS context or original CSS stylesheet file.

  • Default: file
  • Required: false
  • Options: file|rule
filterBy

Defines filter functions that will manipulate the list of images founded in your stylesheet(s).

  • Default: []
  • Required: false
  • Options: Function|Function[]

Every function must return a Promise which should be resolved or rejected.

Built-in filters:

  • based on fs.stat and used to remove non exisiting images
groupBy

Defines group functions that will manipulate the list of images founded in your stylesheet(s).

  • Default: []
  • Required: false
  • Options: Function|Function[]

Every function must return a Promise which should be resolved with a string or rejected.

Built-in filters:

  • based on @2x naming convention
retina

Defines whether or not to search for retina mark in the filename.

  • Default: false
  • Required: false
hooks

Defines whether or not to search for retina mark in the filename.

  • Default: {}
  • Required: false
hooks.onSaveSpritesheet

Hook that allows to rewrite the data of produced spritesheet.

If returned value is string, it is used as filepath value, and if returned value is object, it is used as value which will be merged with current spritesheet data.

Returned value can also be Promise which should return either string or object.

  • Default: null
  • Required: false
hooks.onUpdateRule

Hook that allows to rewrite the CSS output for an image.

  • Default: null
  • Required: false
spritesmith

A spritesmith configuration.

  • Default: {}
  • Required: false
spritesmith.engine

The engine.

  • Default: pixelsmith
  • Required: false
spritesmith.algorithm

The algorithm.

  • Default: binary-tree
  • Required: false
spritesmith.padding

The space between images in spritesheet.

  • Default: 0
  • Required: false
spritesmith.engineOpts

The configuration of the engine.

  • Default: {}
  • Required: false
spritesmith.exportOpts

The export options of the engine.

  • Default: {}
  • Required: false
svgsprite

A svg-sprite configuration.

verbose

Prints the plugin output to the console.

  • Default: false
  • Required: false

The Image

Every filter or group function will be called with an Image object.

styleFilePath

An absolute path to the stylesheet - /Path/to/your/source/stylesheet.css

path

An absolute path to the image - /Path/to/your/image.png

originalUrl

The url found in your stylesheet including the query params - ../image.png?v1

url

A normalized version of the original url - ../image.png

ratio

The retina ratio of your image - 2

retina

Indicates whenever your image is retina - true

groups

The groups associated with the image - ['shapes', '@2x']

token

The string used as reference in your stylesheet - /* @replace|image.png */

coords

The position & dimensions of image in generated spritesheet - { width: 20, height: 20, x: 0, y: 0 }

spritePath

A relative path to the generated spritesheet - dist/sprite.png

spriteUrl

A CSS url to the generated spritesheet - sprite.png

spriteWidth

The total width of the spritesheet - 200

spriteHeight

The total height of the spritesheet - 400


Advanced


Contributing

Pull requests are welcome.

$ git clone [email protected]:2createStudio/postcss-sprites.git
$ npm install
$ npm run watch

postcss-sprites's People

Contributors

bivihoba avatar cattail avatar jednano avatar jiagang avatar koppthe avatar niksy avatar redforks avatar vvasilev- avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

postcss-sprites's Issues

why the β€œbackground-repeat” is missing?

I have a question.
my css like this:

background: url('images/iconfont-wuliuguanli.png') no-repeat;

postcss-sprites process result like this:

background-image: url(images/sprite.png);
background-position: 0 0;

Why the "no-repeat" is missing?Thanks in advance!

[Question] Prevent re-declare background-image

Hello, is there any way to prevent declaring background-image again and again?

.comment { background-image: url(images/sprite.png); background-position: 0 0; }
.bubble { background-image: url(images/sprite.png); background-position: 0 -50px; }

i expect just like these following lines.

.icon { background-image: url(images/sprite.png); }
.comment { background-position: 0 0; }
.bubble { background-position: 0 -50px; }

Thanks for built an amazing plugins πŸ˜„

Disable console warnings

Would you consider adding option to disable console warnings (i.e. postcss-sprites: Skip assets/images/image.png because doesn't exist.)? Complicated build processes which contain image URL rewriting before postcss-sprites does it’s work make it really "loud" in CLI :)

spritePath with variable generates directory of the variable name.

I want to use spritePath with variable, but postcss-sprites does not recognize variable as expected.
I think '<%= path.dist %>/img/sprites.png' should be convert to ./dist/img/sprites.png.

Running "postcss:dist" (postcss) task
20 Nov 13:14:04 - [postcss-sprites] => Spritesheet <%= path.dist %>/img/sprites.png generated.
20 Nov 13:14:04 - [postcss-sprites] => Done.
>> 1 processed stylesheet created.

Done, without errors.

Below is my Grunfile.

module.exports = function (grunt) {

  require('time-grunt')(grunt);
  require('jit-grunt')(grunt);

  grunt.initConfig({

    path: {
      src: './src',
      dist: './dist'
    },

    clean: {
      all: ['<%= path.dist %>']
    },

    copy: {
      all: {
        files: [
          {
            expand: true,
            cwd: '<%= path.src %>/img/',
            src: '**/*.*',
            dest: '<%= path.dist %>/img/'
          }
        ]
      }
    },

    sass: {
      all: {
        files: [
          {
            expand: true,
            cwd: '<%= path.src %>/scss',
            src: '*.scss',
            dest: '<%= path.dist %>/css',
            ext: '.css'
          }
        ]
      }
    },

    postcss: {
      options: {
        sourcemap: true,
        processors: [
          require('postcss-sprites')({
            stylesheetPath: '<%= path.dist %>/css',
            spritePath: '<%= path.dist %>/img/sprites.png'
          })
        ]
      },
      dist: {
        src: '<%= path.dist %>/css/index.css'
      }
    }
  });

  grunt.registerTask('default', ['clean']);
  grunt.registerTask('build', ['clean', 'copy', 'sass', 'postcss']);
};

Color formats

The plugin should be able to extract the following color formats to background-color:

  • hex
  • rgb
  • rgba

Insert image dimensions

Thanks for the excellent plugin! How do I get the image dimension declarations in there too? I don't see the value in referencing a sprite sheet w/o also including width and height for the image within the sprite sheet. Am I missing something?

Question. How to avoid sprites overwriting

Here is my file structure
structure

I'm using webpack

sidebar/icons.scss

.actionExit {
    background: url("images/exit.png");
    size: 26px 20px;
}

.actionMenu {
    background: url("images/menu.png");
    size: 19px 13px;
}

.actionStat {
    background: url("images/graph.png");
    size: 24px 20px;
}

//and so on

dashboard-notifications-area/styles.scss

.bubble {
    position: relative;
    top: 20px;
    left: 20px;
    size: 108px;
    background: url("bubble.png");
    color: white;
    text-align: center;
}

plugin configuration

sprites( {
            spritesmith: { padding: 10 },
            spritePath: './dist/assets'
        })

When it compiles the output is like

postcss-sprites: 0 spritesheet generated.
postcss-sprites: 0 spritesheet generated.
postcss-sprites: 0 spritesheet generated.
postcss-sprites: 1 spritesheet generated.
postcss-sprites: 1 spritesheet generated.

It generates two different spritesheets for each .scss file, and obviously the second, overrides the first one, and i get in the sprite.png only the sprite for bubble.png

How to tell the plugin to merge all of it to one file, and don't create a new sprite.png per each .scss file

Seemingly no support for JPEGs

The plugin doesn't seem to be supporting JPEGs, despite Spritesmith's (well, the default engine pixelsmith) support.

Environment:
Windows 7 / Node 0.12.4 / Grunt-CLI 0.1.13

Grunt task:

postcss: {
    options: {
        map: true,
        processors: [
            require('postcss-sprites')({
                spritePath: './client-side/dist/images/',
                spriteName: 'sprite.png',
                retina: true
            })
        ]
    },
    dist: {
        src: '<%= dirs.src %>/pcss/app.pcss',
        dest: '<%= dirs.dst %>/css/app.css'
    }
},

The images I tested are simple JPEGs exported from Photoshop with Save for Web. PNGs are sprited correctly.

Verbose output:

Verifying property postcss.dist exists in config...OK
Files: client-side/src/pcss/app.pcss -> client-side/dist/css/app.css
Options: diff=false, map, processors=[null], silent=false
Reading client-side/src/pcss/app.pcss...OK
8 Jun 12:57:16 - [postcss-sprites] => Skip ../images/image-1.jpg - not supported.
8 Jun 12:57:16 - [postcss-sprites] => Skip ../images/image-2.jpg - not supported.
8 Jun 12:57:16 - [postcss-sprites] => Done.
Writing client-side/dist/css/app.css...OK

Any ideas?

How to use in gulp?

This my configuration files,but it doesn't work...
How to configure the file properly?


gulp.task('css', function () {
    var opts = {
        stylesheetPath: './dest',
        spritePath: './dest/images/'
    };
    var processors = [
        autoprefixer,
        cssnext,
        precss,
        sprites(opts)
    ];
    return gulp.src('./src/*.css')
    .pipe(sourcemaps.init())
    .pipe(postcss(processors))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('./dest'));
});

thanks.

SpritePath with variable.

Hi, i have problem with spritePath.
This is me postcss-sprite

var opts = {
stylesheetPath: 'wwwroot/css/main.css',
spritePath: 'wwwroot/i/sprite.png',
retina: true
}

require('postcss-sprites')({
stylesheetPath: '<%= opts.stylesheetPath %>',
spritePath: '<%= opts.spritePath %>',
}),

And when i run this task
[postcss-sprites] => Error: Error: EEXIST, file already exists

External Stylesheet

Add option that allows to generate sprite from folder instead of given CSS.

Problems with loaders of webpack

There are some problems on resolving sprites in sass files with loaders of webpack. Because of the loader, css.source.input.file in postcss is not the right file any more, but the loader's path with !path/to/right/css/file. UIn other words, the image.path will be changed as:

E:\www\Test\react-transform-boilerplate\node_modules\sass-loader\index.js!E:\www\Test\react-transform-boilerplate\src\img\sp-num\1.png

so that all images are not exist.

15 Jan 15:12:31 - [postcss-sprites] => Skip ../img/sp-num/1.png - not exist.

Is there options to fix this case? Or am i lost some key point?

Example config with spritesmith options.

Hello!
How can I set spritesmith options? I try this way, but nothing happens.

var opts    = {
    stylesheetPath  : './dist',
    spritePath      : './dist/images/sprite.png',
    outputDimensions: true,
    spritesmith: {
        padding: 10
    }
};

Add currently processed file to groupBy callback arguments

Currenty, only image object is argument for groupBy callback, but having access to additional properties such as currently processed file and it’s name is useful for situations where you would like to group sprites based on CSS filename or if one file uses same icon from other file and your grouping method allows them to override already existing file.

To make it consistent, adding same rule for filterBy would also be nice.

pretty log and option to disable log

Hi, great plugin. It helps me a lot generating sprites.

Here is a little request. I use this plugin with postcss-cli Could you please format the log so it looks pretty and useful? Now it just prints a few lines of useless logs. And provide an option to disable log?

Thanks.

postcss-sprites: 0 spritesheet generated.
postcss-sprites: 0 spritesheet generated.
postcss-sprites: 0 spritesheet generated.
postcss-sprites: 0 spritesheet generated.

Sprite sheets are no longer generated after v2.0.2

I'm certain that the offending PR is #25. I've already made a comment there.

Here is my input CSS:

/* styles/sheets/foo/index.css */
@import baz;

/** styles/blocks/baz.css */
.icon {
    background: url('../sheets/foo/images/bar.png');
}

I logged some info to the console around line 138.

Before (v2.0.1):

styleFilePath: Z:\project\styles\sheets\foo\index.css
   image.path: Z:\project\styles\sheets\foo\images\bar.png

After (v2.0.2):

styleFilePath: Z:\project\styles\blocks\baz.css
   image.path: Z:\project\styles\blocks\images\bar.png

And here is my configuration:

{
    stylesheetPath: 'build/public/css',
    spritePath: '../public/images/sprites/sprite.png',
    groupBy: image => {
        const group = image.path.split(sep).slice(-3, -2)[0];
        if (image.retina) {
            return `${group}@${image.ratio}x`;
        }
        return group;
    },
    skipPrefix: true,
    outputDimensions: true,
    padding: 10,
    verbose: true,
    retina: true
}

Any ideas how to fix this? I've tried to be as thorough as possible here.

How to use within Grunt?

Hey. I'm attempting to use this plugin within Grunt but keep getting the "no exist" error, and I'm not clear on whether the values for stylesheetPath and spritePath should be relative to the gruntfile, the postcss file being processed, or the output css file.

At present I am referencing the images relatively, so I'm confused as to why they're not found.

Dir structure:

css/ (output directory)
images/
  - sprite/
      spriteImage1.png
      spriteImage2.png
pcss/
  - subfolder/
      spriteStuff.pcss
  main.pcss (includes subfolder/spriteStuff.pcss)
gruntfile.js

And the line within spriteStuff.pcss:

background: url('../../images/sprite/spriteImage1.png');

Any tips as to what's up with this? Thanks!

@2x group repeated many times when used with postcss-cli

the @2x group will be generated many times when used with postcss-cli, so the generated file path is something like sprite.@2x.@2x.@2x.......@2x.@[email protected].

Haven't look into the code carefully.

Currently, I just provide a onSaveSpritesheet hook to filter the unnecessary @2x group.

      onSaveSpritesheet (opts, groups = []) {
        groups = groups.filter((item, index) => {
          return groups.indexOf(item) === index
        })
        // the following line of code is copied from method `makeSpritesheetPath` of the source code
        // which is the default function to generate file path if no onSaveSpritesheet is provided.
        return path.join(opts.spritePath, ['sprite', ...groups, 'png'].join('.'))
      },

Broken on npm 3.3.6 (Node 5.0)

I haven't been able to investigate any root cause, but I can tell you that after upgrading to Node 5.0, sprites are now broken on our app's development server on both Windows and Mac. They are broken in that they don't show at all.

npm install threw errors with node-gyp and fsevents; though, I'm not sure if they are the root cause.

How to use with TypeScript?

The same situation with

TypeError: sprites is not a function
...
import * as sprites from 'postcss-sprites';

const PROCESSORS = [
  ...
  sprites({
    stylesheetPath: `${TMP_DIR}/sprites`,
    spritePath: `${TMP_DIR}/sprites`
  })
];

but solution for TypeScript needed. Thanks in advance

config sprite filename

I want to split css file for each html page and I use gulp with less and postcss, so I have multi less entries. And the result generating sprite for each less entry which is correct, but the filename for the sprite is no readable, as shown below, there is anywhere to config it?
image

Sprite path with groupBy option

If I use the following configuration options:

postcssSprites({
    stylesheetPath: './dist/css',
    spritePath: './dist/images/sprites/sprite.png',
    groupBy: image => {
        return image.path.split(sep).slice(-3, -2)[0];
    }
})

It names each sprite with a sprite prefix.

dist/images/sprites/sprite.foo.png
dist/images/sprites/sprite.bar.png
dist/images/sprites/sprite.baz.png

Is there any way to configure it in such a way that there is no sprite prefix? Like this?

dist/images/sprites/foo.png
dist/images/sprites/bar.png
dist/images/sprites/baz.png

Introduce option to encode data URI

How do you feel about introducing an embedDataUri option to base64-encode the requested image directly in the CSS? I'm thinking this would be useful with postcss-middleware when you want to serve images directly instead of building a sprite sheet every time a CSS file is requested.

Add image resizing

It would be awesome to be able to create sprites of different sizes. Say, if you have large icons for desktop screens, but smaller icons on smartphones. The syntax could be something like this:

variants: [
  '1', // creates a sprite of with dimensions unchanged
  1, // same as above
  '@1x',  // same as above
  '*=1', // same as above
  '-=100', // creates a sprite where all dimensions are reduced by 100px
  '/=4', // creates a sprite where all dimensions are divided by 4
  '25%', // same as above
  '=200' // creates a sprite where dimensions of all images are equal to 200px
]

Also, the API would need to accommodate for setting group-specific options, which is probably a change that needs to happen before this. So the syntax could look something like this:

groups: {
  features: { // creates a group called "features"
    groupBy: '/features/', // matches all images which contain "/features/" in their path
    variants: ['1', '-=200', '/=2'], // creates these variants
    retina: true // creates a retina version of EACH of these variants
  },
  ui: {
    groupBy: function (image) {
      return image.path.indexOf('/ui/') !== -1;
    },
    // ...
  }
  // ...
}

Alternative syntax:

groups: [
  {
    name: 'features',
    // ...
  },
  // ...
]

These are huge changes that need to be discussed, but I believe they would make this plugin even more awesome.

I can also add a PR for this, it would naturally take a while 😁

why an error to use postcss-sprites Responsive Spritesheets

postcss-sprites: An error occurred while processing files - postcss.decl is not a function
TypeError: postcss.decl is not a function
at Object.sprites.hooks.onUpdateRule (D:\nodeJs\postCss\gulpfile.js:36:51)
at D:\nodeJs\postCss\node_modules\postcss-sprites\lib\index.js:464:17
at D:\nodeJs\postCss\node_modules\gulp-postcss\node_modules\postcss\lib\container.js:154:24
at D:\nodeJs\postCss\node_modules\precss\node_modules\postcss\lib\container.js:73:26
at Rule.each (D:\nodeJs\postCss\node_modules\precss\node_modules\postcss\lib\container.js:60:22)
at Rule.walk (D:\nodeJs\postCss\node_modules\precss\node_modules\postcss\lib\container.js:72:21)
at D:\nodeJs\postCss\node_modules\gulp-postcss\node_modules\postcss\lib\container.js:75:32
at Root.each (D:\nodeJs\postCss\node_modules\gulp-postcss\node_modules\postcss\lib\container.js:60:22)
at Root.walk (D:\nodeJs\postCss\node_modules\gulp-postcss\node_modules\postcss\lib\container.js:72:21)
at Root.walkComments (D:\nodeJs\postCss\node_modules\gulp-postcss\node_modules\postcss\lib\container.js:152:21)
at updateReferences (D:\nodeJs\postCss\node_modules\postcss-sprites\lib\index.js:447:7)
at D:\nodeJs\postCss\node_modules\postcss-sprites\lib\index.js:126:11
at tryCatcher (D:\nodeJs\postCss\node_modules\postcss-sprites\node_modules\bluebird\js\release\util.js:16:23)
at Promise._settlePromiseFromHandler (D:\nodeJs\postCss\node_modules\postcss-sprites\node_modules\bluebird\js\release\promise.js:494:35)
at Promise._settlePromise (D:\nodeJs\postCss\node_modules\postcss-sprites\node_modules\bluebird\js\release\promise.js:555:18)
at Promise._settlePromise0 (D:\nodeJs\postCss\node_modules\postcss-sprites\node_modules\bluebird\js\release\promise.js:600:10)

sprites is not a function

Hi,

I'm having a strange error when i'm trying to use gulp with postcss-sprites (3.0.2) but when i use v2.0.3 it's working.

Here is my code;

var postcss = require('gulp-postcss');
var sprites = require('postcss-sprites');

var postcssModules = [
    sprites({ //line 40 in erros
       basePath: './src/',
       stylesheetPath: './src/scss/',
       spritePath: './assets/img/'
    })
]

gulp.task('sass', function () {
      return gulp.src('./src/scss/style.scss')
         .pipe(postcss(postcssModules))
         .pipe(gulp.dest('./assets/css'))
});

Here is my error;

sprites is not a function
at Object.<anonymous> (/Users/user/Desktop/projectname/gulpfile.js:40:5)
at Module._compile (module.js:397:26)
at Object.Module._extensions..js (module.js:404:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Liftoff.handleArguments (/usr/local/lib/node_modules/gulp/bin/gulp.js:116:3)
at Liftoff.<anonymous> (/usr/local/lib/node_modules/gulp/node_modules/liftoff/index.js:181:16)
at module.exports (/usr/local/lib/node_modules/gulp/node_modules/liftoff/node_modules/flagged-respawn/index.js:17:3)
at Liftoff.<anonymous> (/usr/local/lib/node_modules/gulp/node_modules/liftoff/index.js:174:9)
at /usr/local/lib/node_modules/gulp/node_modules/liftoff/index.js:148:9
at /usr/local/lib/node_modules/gulp/node_modules/v8flags/index.js:13:7
at nextTickCallbackWith0Args (node.js:452:9)
at process._tickCallback (node.js:381:13)
at Function.Module.runMain (module.js:431:11)

Spritesheet image buffer as argument to onSaveSpritesheet

Would it be possible (and make sense) to add final spritesheet buffer image as argument to onSaveSpritesheet hook?

Use case: you want to name your final files based on exact content inside those images, and you would hash final filename with module like hasha. This way you always get final filename inside your styles based on exact content. Currently the only way I can see that you can get different filename is with some external argument, but you loose caching of large images even if they didn’t change. With hashing final buffer this is avoided.

PostCSS Plugins Guidelines

PostCSS Plugins Guidelines are ondatory for all PostCSS plugins. You need quickly fix:

  • 1.4 Create plugin by postcss.plugin
  • 2.1. Plugin must be tested
  • 4.2. Put input and output examples
  • 4.4. postcss-plugin keyword in package.json

I suggested a 2 steps plan. We need to fix 1.4, 4.2 and 4.4 today and test can be written on this week.

/cc @vvasilev-

Percentage-based backgrounds?

Hello! I'm looking to switch over to PostCSS from Compass. I mostly use Compass for spriting. Your plugin came highly recommended and looks aces! However, there's something I need that it doesn't do... but Compass does:

Provide background positioning and sizing in percentages.

It's very useful when doing responsive sprite animations where you want the image to stay a certain size in relation to the content.

Any chance this is on the way? I can provide some math if that helps :)

Check build into source control

Having prepublish build into the ignored lib directory makes it difficult to fork the repo, dev on a branch, open a PR, and then point a project to the fork while waiting for the PR to merged upstream.

Add option to walk @-rules to cover Sass mixins

Currently, plugin only walks through standard CSS selectors with walkRules, but using Sass you can define mixins with @mixin so you can define your sprite in one place and then reuse them at different places in your style codebase.

@mixin icon {
    background-image:url('icon.png');
}

Is it possible to add option to walk @-rules with walkAtRules, maybe through custom config property?

No visible success, no error

I can't get this to work at all. I'm even starting to doubt what this plugin is supposed to do. Is it supposed to generate the actual spritesheet image and put it in spritePath? Either way, I'm not seeing results in terms of images or changes to output CSS. Here's my nodejs file I'm running (attempting to run the CLI didn't work).

var fs = require('fs');
var postcss = require('postcss');

var css = fs.readFileSync('./css/cg_style.css', 'utf8');

postcss([ require('postcss-sprites').default ])
    .process(css, { 
      relativeTo: 'rule',
      stylesheetPath: './css',
      spritePath: './img'
    })
    .then(function (result) {
      fs.writeFileSync('./css/app.css', result.css);
    });

Add imagePath option

This would enable postcss-sprite to resolve url('/images/...') paths. If you like the idea, I could submit a PR.

Wrong path in multi-level dir

Hi,
I got a wrong path when using sprites in different level directories. e.g.

app/
  img/
    sp-num1/
    sp-num2/
  css/
    x.css
    folder/
      y.css

Code in x.css :

.class1 {
    background: url('../img/sp-num/1.png');
}
.class2 {
    background: url('../img/sp-num/2.png');
}

Code in y.css :

.class1 {
    background: url('../../img/sp-num2/3.png');
}
.class2 {
    background: url('../../img/sp-num2/4.png');
}

After transforming, y.css got a wrong url path:

.class1 {
    background: url('../img/sp-num2.png');
}

Right url should be ../../img/sp-num2.png.


Review the source code, line 459:

image.spriteUrl = _path2.default.relative(opts.stylesheetPath, image.spritePath);

should be replaced by:

var styleFilePath = opts.relativeTo === RELATIVE_TO_RULE ? rule.source.input.file : root.source.input.file;
image.spriteUrl = _path2.default.relative(_path2.default.dirname(styleFilePath), image.spritePath);

Please check this.

Skipped images do not appear

If I skip an image, this happens:

#home-buttons a.what-is         { /*@replace|../images/images/hb-what-is-phpbb.png*/ }
#home-buttons a.get-started     { /*@replace|../images/images/hb-get-started.png*/ }
#home-buttons a.enhance         { /*@replace|../images/images/hb-enhance-phpbb.png*/ }
#home-buttons a.contribute      { /*@replace|../images/images/hb-contribute.png*/ }

Why? Wouldn't it be better to leave it as is and let the browser handle the error, instead of dying silently?

Thanks for this plugin, by the way! looks like it is going to be super useful

Using postcss-sprites with gulp

Hello! Earlier I used [email protected] with [email protected] plugin, but when I updated it to 6.0.0 it isn't work.

My gulpfile.js config is:

/* a lot of require's sections is  */

var preprocessors = [
    postcssImport({from: './'}),
    autoprefixer({ browsers: ['last 2 versions'] }),
    postcssMixins,
    postcssNested,
    postcssfor,
    postcssVars,
    postcssColor,
    cssnext,
    cssnano,
    sprites(opts)
  ];

gulp.task('styles', function () {
    return gulp.src($config.cssMain)
        .pipe($.sourcemaps.init())
        .pipe($.postcss(preprocessors))
        .pipe($.rename($config.cssOutputName))
        .pipe($.sourcemaps.write('.'))
        .pipe(gulp.dest($config.cssOutput));
  });

change warning to log

.spread((root, opts, images, spritesheets) => {
     result.warn(`${spritesheets.length} ${spritesheets.length > 1 ? 'spritesheets' : 'spritesheet'} generated.`);
 })

I think this message just tell us the number of generated spritesheet, it should be simple log, but not a warning. And postcss-reporter and postcss-browser-reporter will collect these message if we treat it as warning

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.