CSS Modules

What are CSS Modules?

CSS modules are CSS files in which all class names and animation names are scoped locally by default.

So CSS Modules is not an official spec or an implementation in the browser but rather a process in a build step (with the help of Webpack or Browserify) that changes class names and selectors to be scoped (i.e. kinda like namespaced).

CSS Modules compile to a low-level interchange format called ICSS or Interoperable CSS, but are written like normal CSS files. By treating the CSS as a dependency of our JS, we have the opportunity to do something hitherto impossible – pass variables from CSS to JS. When importing the CSS Module from a JS Module, it exports an object with all mappings from local names to global names.

Why?

modular and reusable CSS!

  • No more conflicts.

  • Explicit dependencies.

  • No global scope.

Features

  • Local by default. In CSS Modules, each file is compiled separately so you can use simple class selectors with generic names — you don’t need to worry about polluting the global scope. The actual classnames are automatically generated and guaranteed to be unique. CSS Modules takes care of all that for you, and compiles the files to a format called ICSS, which is how CSS and JS can communicate.

  • Composition. With of composes, you can combine multiple separate groups of styles without changing your markup or rewriting your CSS selectors.

  • Sharing between files. CSS Modules runs on a single file at a time, so there’s no global context to pollute. And like in JavaScript where we can import or require our dependencies, CSS Modules lets us compose from another file.

Pros and cons

pros:

  • We work with regular CSS, it makes it possible to use SCSS, Less, Postcss, stylelint, and more. Also, you don't waste time on adapting the CSS to JS.

  • No integration of styles into the code, clean code as result.

  • Almost 100% standardized except for global styles.

cons:

  • To describe global styles, you must use a syntax that does not belong to the CSS specification.

:global(.myclass) {
    text-decoration: underline;
}
  • Integrating into a project, you need to include styles.

  • Working with typescript, you need to automatically or manually generate interfaces. For these purposes.

Last updated

Was this helpful?