Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
postcss-modules
Advanced tools
The postcss-modules package is a PostCSS plugin that enables CSS Modules, a technique for locally scoping CSS by automatically creating a unique classname of the format [filename]__[local classname]__[hash]. This helps in avoiding global scope pollution in CSS and makes component-based development easier and more maintainable.
Local Scope for CSS Classes
This feature automatically scopes class names locally rather than globally. This is done by appending a unique hash to each class name, which makes them unique across the project. This prevents styles from leaking into other parts of the application unintentionally.
/* Input CSS */
.className {
color: red;
}
/* Output CSS */
.fileName__className__hash {
color: red;
}
Composition of Styles
This feature allows CSS classes to compose from other classes, potentially from different files. This promotes reusability of CSS styles and helps in maintaining a cleaner and more organized stylesheet architecture.
/* Input CSS */
.className {
composes: anotherClass from './anotherStyle.css';
color: red;
}
/* Output CSS */
.fileName__className__hash {
color: red;
}
.fileName__anotherClass__hash {
/* styles from anotherClass */
}
css-loader is a webpack loader that interprets @import and url() like import/require() and will resolve them. It also offers modules functionality similar to postcss-modules, where it localizes CSS by default using similar scoping rules. Compared to postcss-modules, css-loader is tightly integrated with webpack's module system, which might be preferable in webpack-based projects.
styled-components is a library for React and React Native that allows CSS to be written inside JavaScript files by tagging template literals. This approach scopes styles by generating unique class names at runtime. Unlike postcss-modules, styled-components embeds styles directly into components, which can enhance runtime performance and offers enhanced theming capabilities.
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",
}
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) {
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
.
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]',
})
]);
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:\',
});
]);
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"
}
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>
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>
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-modules
0.7.0
FAQs
PostCSS plugin to use CSS Modules everywhere
The npm package postcss-modules receives a total of 600,129 weekly downloads. As such, postcss-modules popularity was classified as popular.
We found that postcss-modules demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.