@carbonorm/postcss-modules

中文文档
6.0.2发布于 2023/07/28MITTypeScriptCommonJS近 30 天下载 3418

PostCSS plugin to use CSS Modules everywhere

原始使用文档
文档目录13 节
  1. What is this?
  2. Usage
  3. Saving exported classes
  4. Generating scoped names
  5. Exporting globals
  6. Loading source files
  7. localsConvention
  8. Resolve path alias
  9. Integration with templates
  10. Pug (ex-Jade)
  11. HTML
  12. May I see the plugin in action?
  13. Sponsors

postcss-modules

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

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

Saving exported classes

By default, a JSON file with exported classes will be placed next to corresponding CSS. But 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, outputFileName) {
            var path = require("path");
            var cssName = path.basename(cssFileName, ".css");
            var jsonFileName = path.resolve("./build/" + cssName + ".json");
            fs.writeFileSync(jsonFileName, JSON.stringify(json));
        },
    }),
]);

getJSON may also return a Promise.

Generating scoped names

By default, the plugin assumes that all the classes are local. You can change this behaviour using the scopeBehaviour option:

postcss([
    require("postcss-modules")({
        scopeBehaviour: "global", // can be 'global' or 'local',
    }),
]);

To define paths for global modules, use the globalModulePaths option. It is an array with regular expressions defining the paths:

postcss([
  require('postcss-modules')({
    globalModulePaths: [/path\/to\/legacy-styles/, /another\/paths/],
  });
]);

To generate custom classes, use the generateScopedName callback:

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

            return "_" + file + "_" + line + "_" + name;
        },
    }),
]);

Or just pass an interpolated string to the generateScopedName option (More details here):

postcss([
    require("postcss-modules")({
        generateScopedName: "[name]__[local]___[hash:base64:5]",
    }),
]);

It's possible to add custom hash to generate more unique classes using the hashPrefix option (like in css-loader):

postcss([
    require("postcss-modules")({
        generateScopedName: "[name]__[local]___[hash:base64:5]",
        hashPrefix: "prefix",
    }),
]);

Exporting globals

If you need to export global names via the JSON object along with the local ones, add the exportGlobals option:

postcss([
    require("postcss-modules")({
        exportGlobals: true,
    }),
]);

Loading source files

If you need, you can pass a custom loader (see FileSystemLoader for example):

postcss([
    require("postcss-modules")({
        Loader: CustomLoader,
    }),
]);

You can also pass any needed root path:

postcss([
  require('postcss-modules')({
    root: 'C:\\',
  });
]);

localsConvention

Type: String | (originalClassName: string, generatedClassName: string, inputFile: string) => className: (string|string[]) Default: null

Style of exported classnames, the keys in your json.

NameTypeDescription
'camelCase'{String}Class names will be camelized, the original class name will not to be removed from the locals
'camelCaseOnly'{String}Class names will be camelized, the original class name will be removed from the locals
'dashes'{String}Only dashes in class names will be camelized
'dashesOnly'{String}Dashes in class names will be camelized, the original class name will be removed from the locals
'all'{String}Apply camelCase, dashes, and the orignional naming convention
'none'{String}Only use the orignional naming convention with out locals

In lieu of a string, a custom function can generate the exported class names.

Resolve path alias

You can rewrite paths for composes/from by using the resolve option. It's useful when you need to resolve custom path alias.

Parameters:

  • file — a module we want to resolve
  • importer — the file that imports the module we want to resolve

Return value: string | null | Promise<string | null>

postcss([
    require("postcss-modules")({
        resolve: function (file, importer) {
            return path.resolve(
                path.dirname(importer),
                file.replace(/^@/, process.cwd()
            );
        },
    }),
]);

Integration with templates

The plugin only transforms CSS classes to CSS modules. But you probably want to integrate these CSS modules with your templates. Here are some examples.

Assume you've saved project's CSS modules in cssModules.json:

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

Pug (ex-Jade)

Let's say you have a Pug template about.jade:

h1(class=css.title) postcss-modules
article(class=css.article) A PostCSS plugin to use CSS Modules everywhere

Render it:

var jade = require("jade");
var cssModules = require("./cssModules.json");
var html = jade.compileFile("about.jade")({ css: cssModules });
console.log(html);

And you'll get the following HTML:

<h1 class="_title_xkpkl_5 _title_116zl_1">postcss-modules</h1>
<article class="_article_xkpkl_10">
    A PostCSS plugin to use CSS Modules everywhere
</article>

HTML

For HTML transformation we'll use PostHTML and PostHTML CSS Modules:

npm install --save posthtml posthtml-css-modules

Here is our template about.html:

<h1 css-module="title">postcss-modules</h1>
<article css-module="article">
    A PostCSS plugin to use CSS Modules everywhere
</article>

Transform it:

var fs = require("fs");
var posthtml = require("posthtml");
var posthtmlCssModules = require("posthtml-css-modules");
var template = fs.readFileSync("./about.html", "utf8");

posthtml([posthtmlCssModules("./cssModules.json")])
    .process(template)
    .then(function (result) {
        console.log(result.html);
    });

(for using other build systems please check the documentation of PostHTML)

And you'll get the following HTML:

<h1 class="_title_xkpkl_5 _title_116zl_1">postcss-modules</h1>
<article class="_article_xkpkl_10">
    A PostCSS plugin to use CSS Modules everywhere
</article>

May I see the plugin in action?

Sure! Take a look at the example.

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

npm install --save-dev postcss postcss-modules

Sponsors

  • Dmitry Olyenyov

版本与发布记录

@carbonorm/postcss-modules 共发布 2 个版本,首次发布于 2023/07/28;过去 12 个月发布了 0 个版本。

版本发布日期距今
6.0.2latest2023/07/283 年前
6.0.12023/07/283 年前

关于 @carbonorm/postcss-modules 的常见问题

@carbonorm/postcss-modules 是什么?

PostCSS plugin to use CSS Modules everywhere

如何安装 @carbonorm/postcss-modules?

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

@carbonorm/postcss-modules 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@carbonorm/postcss-modules 支持 ESM 还是 CommonJS?

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

@carbonorm/postcss-modules 可以商用吗?

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

@carbonorm/postcss-modules 的下载量有多少?

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

@carbonorm/postcss-modules 还在维护吗?

最新版本 6.0.2 发布于 2023/07/28(3 年前);至今共发布 2 个版本,其中过去 12 个月发布了 0 个;首次发布于 2023/07/28。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。