The require hook compiles CSS Modules in runtime. This is similar to Babel's babel/register.
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.
Compiling in runtime, universal usage.
To use this tool we require Node.js v0.12.x (or higher) and several modules to be installed.
- postcss version 4 or higher
- postcss-modules-extract-imports
- postcss-modules-local-by-default
- postcss-modules-scope
$ npm i css-modules-require-hookfunctioncreateImportedName — short alias for the postcss-modules-extract-imports plugin'screateImportedNameoption.functiongenerateScopedName — 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.functionprocessCss — in rare cases you may want to get compiled styles in runtime, so providing this option helps.stringrootDir — 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.stringto — providestooption to the LazyResult instance.arrayuse — custom subset of postcss plugins.arrayextensions — attach the hook to additional file extensions (for example['.scss']).
Basically you need to load this module before you start loading css-modules. Otherwise you'll get an exception. For example:
icon.css
.icon { composes: fa fa-hand-peace-o from 'font-awesome/css/font-awesome.css'; }server.js
require('css-modules-require-hook'); var styles = require('./icon.css'); var html = '<i class="' + styles.icon + '"></i>'; // send it somehow :)You'll get:
<i class="_icon_font-awesome-css-font-awesome__fa _icon_font-awesome-css-font-awesome__fa-hand-peace-o"></i>'In rare cases you may want to tune the require hook for better experience.
var hook = require('css-modules-require-hook'); var path = require('path'); hook({ // setting root to the parent directory rootDir: path.join(__dirname, '..') });If you want to add any postcss plugins to the pipeline - you should use the use option.
var hook = require('css-modules-require-hook'); hook({ use: [ // adding CSS Next plugin require('cssnext')(), // adding basic css-modules plugins require('postcss-modules-extract-imports'), require('postcss-modules-local-by-default'), require('postcss-modules-scope') ] });