Becoming A Developer — Implementing CSS Modules with Vanilla Javascript and Webpack -Part 1

Ogbonna Basil
2 min readOct 2, 2018

Simple websites/apps ranging few pages can have layouts set using traditional style sheets with selectors, id’s, classes and attributes. However, for web pages ranging from tens into hundreds, using traditional CSS methods becomes a daunting task. The problem arises in two forms, specificity, and scalability.
Various methods have been used to solve this problem including the use of CSS preprocessors like Sass and LESS, Block Element Modifiers, Styled components, and CSS Modules.
What are CSS Modules?
A CSS Module is a CSS file in which all class names are scoped locally by default. They eradicate the need for complex BEM naming style. They are simply CSS files imported into Javascript which then assigns a unique class name for each element. By providing a local scope for classes, specificity problems are solved. There is no need to uncomment many lines of CSS codes and start re-writing. Assigning class names becomes easier for pages. This makes the approach scalable.

Implementing CSS Modules
Your CSS file looks like this:

.red{
background-color:red
}

background.css
This is then imported into a javascript file say index.js (ES6 syntax).

import background from ‘../components/background.css’

This is bundled and assigned a local scope name by default in your build process.

.background__red___2r6A{
background-color:red
}

which can be used in any HTML page by simply inserting the built javascript inside the HTML script tag.

<script type=”text/javascript” src=”js/index.js?c9f166b70ad453cd178c”></script>

Why Webpack?
Local scoping is implemented in the build step and for that, you need a bundler like Webpack or Browserify.
Webpack bundles javascript files, stylesheets, images and generates one or more bundles needed in your project.
Vanilla Javascript or Javascript Frameworks?
It is easier to implement CSS Modules using javascript frameworks like React. However, for an absolute beginner, it would be better to understand how CSS Modules are implemented using pure (Vanilla) javascript.
To Implement CSS Modules follow the steps below.
- Install webpack ( I prefer using node.js to install it as a dependency)
- Install relevant webpack plugins ( mini-css extract plugin, css-loader plugin)
- Configure properly the webpack.config.js file
- Write CSS components and HTML pages
- Run the build process
Part 2 of this post will follow these steps in demystifying CSS Modules.

--

--