• Stars
    star
    485
  • Rank 90,698 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 9 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A require hook to compile CSS Modules in runtime

css-modules-require-hook

The require hook compiles CSS Modules in runtime. This is similar to Babel's babel/register. See the example: demo.

What is CSS Modules

A CSS Module is a CSS file in which all class names and animation names are scoped locally by default. Learn more in the article CSS Modules - Welcome to the Future by Glenย Maddern.

Features

Compiling in runtime, universal usage.

Requirements

To use this tool we require Node.js v0.12.x (or higher).

Installation

$ npm i css-modules-require-hook

Usage

Now, there are two ways to attach hook: manually or using preset file.

The first one allows you to pass options manually after module was required. Example:

const hook = require('css-modules-require-hook');

hook({
  generateScopedName: '[name]__[local]___[hash:base64:5]',
});

// const styles = require('./icon.css');

The second one allows you to move options to the separate file cmrh.conf.js. Config file should be located in the same directory where executor is or in its ancestor directories. In that case hook will be attached right after the css-modules-require-hook/preset module will be required. Example:

// cmrh.conf.js
module.exports = {
  generateScopedName: '[name]__[local]___[hash:base64:5]',
};
require('css-modules-require-hook/preset');

// const styles = require('./icon.css');

Using with babel-node / ES6 Imports

You will need to create a cmrh.conf.js file within the directory as you are importing css-modules-require-hook.

// server.js
import csshook from 'css-modules-require-hook/preset' // import hook before routes
import routes from '/shared/views/routes'

// create server, etc
// cmrh.conf.js
module.exports = {
  // Same scope name as in webpack build
  generateScopedName: '[name]__[local]___[hash:base64:5]',
}

Development mode

Usually, Node.js caches all the require calls by default. In order to invalidate cache for the purpose of development you should set the environment variable NODE_ENV to development. For example:

$ NODE_ENV=development node server.js

Still you can use devMode option (see below) to override behavior which is imposed by environment variable.

Adding custom PostCSS plugins

var hook = require('css-modules-require-hook');
var cssnext = require('cssnext');

hook({
  prepend: [
    // adding CSS Next plugin
    cssnext(),
  ],
});

Specify custom pattern to build generic names

var hook = require('css-modules-require-hook');

hook({
  generateScopedName: '[name]__[local]___[hash:base64:5]',
});

Using Stylus as a preprocessor

var hook = require('css-modules-require-hook');
var stylus = require('stylus');

hook({
  extensions: ['.styl'],
  preprocessCss: function (css, filename) {
    return stylus(css)
      .set('filename', filename)
      .render();
  },
});

// var styles = require('./demo.styl');

Tuning (options)

To adjust the require hook you need to provide params to the exported function.

var hook = require('css-modules-require-hook');

hook({
  // append: [],
  // generateScopedName: function () {},
  // or any other options
  // see the list below
});

devMode boolean

Helps you to invalidate cache of all require calls. Usually used for the development purpose. Also overrides behavior, imposed by NODE_ENV environment variable. For example:

hook({
  devMode: false,
});

extensions array

Attach the require hook to additional file extensions (for example ['.scss']).

ignore function|regex|string

Provides possibility to exclude particular files from processing. Supports glob and regular expressions syntax. Also you may provide custom function.

preprocessCss function

In rare cases you may want to precompile styles, before they will be passed to the PostCSS pipeline. You should use synchronous transformations, since require function is synchronous.

hook({
  /**
   * @param  {string} css
   * @param  {string} filepath Absolute path to the file
   * @return {string}
   */
  preprocessCss: function (css, filepath) {
    return css;
  }
});

processCss function

In rare cases you may want to get compiled styles in runtime, so providing this option helps.

hook({
  /**
   * @param  {string} css
   * @param  {string} filepath Absolute path to the file
   */
  processCss: function (css, filepath) { /* */ }
});

processorOpts object

Provides possibility to pass custom options to the LazyResult instance. It can be usefull if you want to set the custom parser, for example: postcss-less.

const hook = require('css-modules-require-hook');
const lessParser = require('postcss-less').parse;

hook({
  extensions: '.less',
  processorOpts: {parser: lessParser},
});

camelCase boolean|string

Camelizes exported class names. Similar to css-loader?camelCase.

Available options: true, dashes, only, dashesOnly.

append array

Appends custom plugins to the end of the PostCSS pipeline. Since the require function is synchronous, you should provide synchronous plugins only.

prepend array

Prepends custom plugins to the beginning of the PostCSS pipeline. Since the require function is synchronous, you should provide synchronous plugins only.

use array

Provides the full list of PostCSS plugins to the pipeline. Providing this cancels append, prepend, createImportedName, generateScopedName options. Synchronous plugins only.

createImportedName function

Short alias for the postcss-modules-extract-imports plugin's createImportedName option.

generateScopedName string|function

Short alias for the postcss-modules-scope plugin's option. Helps you to specify the custom way to build generic names for the class selectors. You may also use a string pattern similar to the webpack's css-loader.

hook({
  generateScopedName: '[name]__[local]___[hash:base64:5]'
});

or

hook({
  /**
   * @param  {string} name     Usually a class name
   * @param  {string} filepath
   * @param  {string} css
   * @return {string}
   */
  generateScopedName: function (name, filepath, css) {
    return name;
  }
});

hashPrefix string

Short alias for the generic-names helper option. Provides additional hash uniqueness. Might be useful for projects with several stylesheets sharing a same name.

mode string

Short alias for the postcss-modules-local-by-default plugin's option.

resolve object

Changes the way the paths of ICSS imports will be resolved (@value a from './b.css' and composes a from './b.css'). Supports:

  • resolve.alias object
  • resolve.extensions array โ€” default value is ['.css'].
  • resolve.modules array
  • resolve.mainFile string โ€” default value is 'index.css'.
  • resolve.preserveSymlinks boolean โ€” default value is false.

See the detailed description at: https://github.com/css-modules/postcss-modules-resolve-imports#options

rootDir string

Provides absolute path to the project directory. Providing this will result in better generated class names. It can be obligatory, if you run require hook and build tools (like css-modulesify) from different working directories.

Debugging

debug package is used for debugging. So to turn it on simply specify the DEBUG environment variable:

  • DEBUG=css-modules:fetch โ€” to see resolved paths to the files.
  • DEBUG=css-modules:preset โ€” to see whether config was found or not.
  • DEBUG=css-modules:setup โ€” to see the new options list.
  • DEBUG=css-modules:* โ€” to see everything.

Links

License

The MIT License

More Repositories

1

css-modules

Documentation about css-modules
17,621
star
2

webpack-demo

Working demo of CSS Modules, using Webpack's css-loader in module mode
JavaScript
1,487
star
3

icss

Interoperable CSS โ€” a standard for loadable, linkable CSS
612
star
4

css-modulesify

A browserify plugin to load CSS Modules
JavaScript
406
star
5

postcss-icss-values

Pass arbitrary constants between your module files
JavaScript
202
star
6

css-modules-loader-core

A loader-agnostic CSS Modules implementation, based on PostCSS
JavaScript
92
star
7

browserify-demo

A working demo of CSS Modules, using css-modulesify
JavaScript
87
star
8

css-selector-tokenizer

Parses and stringifies CSS selectors.
JavaScript
84
star
9

postcss-icss-composes

A CSS Modules transform to extract export statements from local-scope classes
JavaScript
55
star
10

jspm-demo

CSS Modules & JSPM
JavaScript
52
star
11

postcss-modules-extract-imports

A CSS Modules transform to extract local aliases for inline imports
JavaScript
40
star
12

postcss-modules-values

Pass arbitrary constants between your module files
JavaScript
35
star
13

postcss-modules-scope

A CSS Modules transform to extract export statements from local-scope classes
JavaScript
23
star
14

icss-utils

Search & replace tokens during the linking stage of ICSS loading
JavaScript
22
star
15

postcss-modules-local-by-default

PostCSS plugin for css modules to local-scope classes and ids
JavaScript
20
star
16

cssm-rails

WIP of a Rails plugin for CSS Modules
Ruby
17
star
17

generic-names

Helper for building generic names, similar to webpack
JavaScript
15
star
18

postcss-modules-resolve-imports

Resolves ICSS imports
JavaScript
9
star
19

postcss-modules-lint

PostCSS plugin to verify the scoping of selectors in CSS Modules
JavaScript
8
star
20

logos

Official CSS Modules logos
5
star
21

postcss-icss-keyframes

PostCSS plugin for css-modules to local-scope keyframes
JavaScript
5
star
22

postcss-icss

Postcss plugin to process css modules and extract tokens
JavaScript
4
star
23

postcss-icss-import

PostCSS plugin for css-modules to convert @import statements to ICSS
JavaScript
2
star
24

postcss-icss-url

JavaScript
2
star