@dr.pogodin/css-modules-require-hook

中文文档
4.7.3发布于 2023/04/09MITCommonJS近 30 天下载 1.1万

A require hook to compile CSS Modules on the fly

此软件包已被标记为弃用

Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.

原始使用文档
文档目录30 节
  1. What is CSS Modules
  2. Features
  3. Requirements
  4. Installation
  5. Usage
  6. Using with babel-node / ES6 Imports
  7. Development mode
  8. Adding custom PostCSS plugins
  9. Specify custom pattern to build generic names
  10. Using Stylus as a preprocessor
  11. Tuning (options)
  12. devMode boolean
  13. extensions array
  14. ignore function|regex|string
  15. preprocessCss function
  16. processCss function
  17. processorOpts object
  18. camelCase boolean|string
  19. append array
  20. prepend array
  21. use array
  22. createImportedName function
  23. generateScopedName string|function
  24. hashPrefix string
  25. mode string
  26. resolve object
  27. rootDir string
  28. Debugging
  29. Links
  30. License

CSS Modules Require Hook

Latest NPM Release NPM Downloads CircleCI GitHub Repo stars

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

Sponsor


This is a fork of css-modules-require-hook upgraded to rely on up-to-date dependencies, and with some issues fixed.


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 install @dr.pogodin/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('@dr.pogodin/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 @dr.pogodin/css-modules-require-hook/preset module will be required. Example:

// cmrh.conf.js
module.exports = {
  generateScopedName: '[name]__[local]___[hash:base64:5]',
};
require('@dr.pogodin/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 @dr.pogodin/css-modules-require-hook.

// server.js
import csshook from '@dr.pogodin/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('@dr.pogodin/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('@dr.pogodin/css-modules-require-hook');

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

Using Stylus as a preprocessor

var hook = require('@dr.pogodin/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('@dr.pogodin/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('@dr.pogodin/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.

License

The MIT License

版本与发布记录

@dr.pogodin/css-modules-require-hook 共发布 15 个版本,首次发布于 2020/04/17;过去 12 个月发布了 0 个版本。

版本发布日期距今
4.7.3latest2023/04/093 年前
4.7.22022/11/163 年前
4.7.12022/11/114 年前
4.7.02022/06/074 年前
4.6.02021/04/255 年前
4.5.12021/04/095 年前

关于 @dr.pogodin/css-modules-require-hook 的常见问题

@dr.pogodin/css-modules-require-hook 是什么?

A require hook to compile CSS Modules on the fly注意:该包已被作者标记为弃用——Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.

如何安装 @dr.pogodin/css-modules-require-hook?

在项目目录运行 npm install @dr.pogodin/css-modules-require-hook,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:postcss(^8)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@dr.pogodin/css-modules-require-hook 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/dr.pogodin__css-modules-require-hook 是否存在。

@dr.pogodin/css-modules-require-hook 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@dr.pogodin/css-modules-require-hook 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >= 14。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@dr.pogodin/css-modules-require-hook 可以商用吗?

@dr.pogodin/css-modules-require-hook 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@dr.pogodin/css-modules-require-hook 的下载量有多少?

根据 npm 官方下载统计,@dr.pogodin/css-modules-require-hook 在 2026/10/13 – 2026/11/11 这 30 天内被下载 11,448 次,日均约 382 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@dr.pogodin/css-modules-require-hook 还在维护吗?

最新版本 4.7.3 发布于 2023/04/09(3 年前);至今共发布 15 个版本,其中过去 12 个月发布了 0 个;首次发布于 2020/04/17。作者已将其标记为弃用,新项目建议寻找替代方案。