zhouwenbin / postcss-modules

PostCSS plugin to use CSS Modules everywhere

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

postcss-modules Build Status

A PostCSS plugin to use CSS Modules everywhere. Not only at the client side.

Sponsored by Evil Martians

What is this? For example, you have the following CSS:

/* styles.css */
:global .page {
    padding: 20px;
}

.title {
    composes: title from "./mixins.css";
    color: green;
}

.article {
    font-size: 16px;
}

/* mixins.css */
.title {
    color: black;
    font-size: 40px;
}

.title:hover {
    color: red;
}

After the transformation it will become like this:

._title_116zl_1 {
    color: black;
    font-size: 40px;
}

._title_116zl_1:hover {
    color: red;
}

.page {
    padding: 20px;
}

._title_xkpkl_5 {
    color: green;
}

._article_xkpkl_10 {
    font-size: 16px;
}

And the plugin will give you a JSON object for transformed classes:

{
  "title": "_title_xkpkl_5 _title_116zl_1",
  "article": "_article_xkpkl_10",
}

Usage

You have a freedom to make everything you want with exported classes, just use the getJSON callback. For example, save data about classes into a corresponding JSON file:

postcss([
  require('postcss-modules')({
    getJSON: function(cssFileName, json) {
      var path          = require('path');
      var cssName       = path.basename(cssFileName, '.css');
      var jsonFileName  = path.resolve('./build' + cssName + '.json');
      fs.writeFileSync(jsonFileName, JSON.stringify(json));
    }
  });
]);

Generate custom classes with the generateScopedName callback:

postcss([
  require('postcss-modules')({
    getJSON: function(cssFileName, json) {},
    generateScopedName: function(name, filename, css) {
      var path      = require('path');
      var i         = css.indexOf('.' + name);
      var numLines  = css.substr(0, i).split(/[\r\n]/).length;
      var file      = path.basename(filename, '.css');

      return '_' + file + '_' + numLines + '_' + name;
    }
  });
]);

See PostCSS docs for examples for your environment and don't forget to run

npm install --save-dev postcss-modules

About

PostCSS plugin to use CSS Modules everywhere

License:MIT License


Languages

Language:JavaScript 100.0%