CSS modular implementation tutorial

As we all know, CSS rules are global, any one component style rules, the entire page is effective.

We want to make a CSS Module by using a unique class name that does not overlap with other selectors.

Here we mainly use CSS-loader and Webpack to implement CSS modules (in fact, automatically generate unique class names).

If you don’t know webpack, it doesn’t matter, then follow me step by step to knock code, I will build the project from scratch, and native JS way to take you to achieve. This is easier to understand if you have a Webpack foundation.

Start by building our project with WebPack

  1. Create a new project name, like I didlearnfolder

  1. Use NPM init -y to generate the package.json file
npm init -y
Copy the code

Create the existing file

  1. Create a SRC folder and create index.js, style. CSS, and index.html files under the SRC folder

The directory is as follows:

The code for the index.js file is as follows:

// index.js
import _ from 'lodash';
import style from './style.css';

 function component() {
   const element = document.createElement('div');

   element.innerHTML = _.join(['Hello'.'webpack'].' ');
   style.hello.split(' ').forEach(item= > element.classList.add(item))

   return element;
 }

 document.body.appendChild(component());
Copy the code

This is using the Lodash package, so let’s follow that in a second

The style. CSS file code is as follows:

.className{
    background-color: #ccc;
}
.hello {
    composes: className;
    color: red;
}
Copy the code

The index.html file code is as follows:

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
    index
</body>
</html>
Copy the code

Installing dependency packages

Here we need to install

  • Babel (parse ES6 code to ES6)
  • Css-loader style-loader
  • Html-webpack-plugin (handles HTML templates)
  • Lodash (js)
  • webpack webpack-cli

So we set it up together

npm i -D babel css-loader  style-loader html-webpack-plugin lodash webpack webpack-cli
Copy the code

After installation

Create a new webpack.config.js file

// webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.js'.output: {
    filename: 'main.js'.path: path.resolve(__dirname, 'dist'),},module: {
    rules: [{test: /\.css$/i,
        use: [
          'style-loader',
          {
            loader: "css-loader".options: {
                modules: true.// Key code to make CSS modular
                // modules: { 
                // localIdentName: "[path][name]__[local]--[hash:base64:5]
                // },},}],},],}plugins: [
    new HtmlWebpackPlugin({
      title: 'cssModule'.template: 'src/index.html'.hash: true})]};Copy the code

All the paperwork is in order to initiate our order. Run

Add a command to run webpakc in package.json

// package.json
"scripts": {
    "build": "webpack"
  },
Copy the code

Execute a wave of commands

npm run build
Copy the code

Package successfully, the files are as follows:

Let’s open up dist/index.html

See, all class names give you hash values, unique class names, and you get the cssModule effect

Global scope

CSS Modules allow you to declare a global rule using the :global(.className) syntax. Any class declared like this will not be compiled to a hash string.

Style.css adds a global class.

/* New CSS */
:global(.g-title) {
    font-size: 20px;
    font-weight: bold;
}
.className{
    background-color: #ccc;
}
.hello {
    composes: className;
    color: red;
}
Copy the code

Index.js uses the normal class notation and references the global class.

import _ from 'lodash';
import style from './style.css';

 function component() {
   const element = document.createElement('div');

   element.innerHTML = _.join(['Hello'.'webpack'].' ');
   style.hello.split(' ').forEach(item= > element.classList.add(item))

   element.classList.add('g-title') // Add new js

   return element;
 }

 document.body.appendChild(component());
Copy the code

Recompile and package

npm run build
Copy the code

The style.css file composes: className; The comPoses inherit the style of the className class. Same as the mixin effect of sASS syntax, except that the composes are recognized by the cssModule

Completed!!!!!! The above is a little brother of some small research, each big guy have any suggestion, welcome message exchange

Reference article: Ruan Yifeng CSS Modules usage tutorial