• Stars
    star
    395
  • Rank 109,040 (Top 3 %)
  • Language
    JavaScript
  • Created over 8 years ago
  • Updated over 8 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

a collection of simple demos of CSS Modules

CSS Modules Demos

This repo is a collection of simple demos of CSS Modules.

If you don't know, CSS Modules is a method to add local scope and module dependencies into CSS.

Usage

First, clone the repo.

$ git clone https://github.com/ruanyf/css-modules-demos.git

Install the dependencies.

$ cd css-modules-demos
$ npm install

Run the first demo.

$ npm run demo01

Open http://localhost:8080 , see the result.

Then run demo02, demo03...

Index

  1. Local Scope
  2. Global Scope
  3. Customized Hash Class Name
  4. Composing CSS Classes
  5. Import Other Modules
  6. Exporting Values Variables

Demo01: Local Scope

demo / sources

CSS rules are global. The only way of making a local-scoped rule is to generate a unique class name, so no other selectors will have collisions with it. That is exactly what CSS Modules do.

The following is a React component App.js.

import React from 'react';
import style from './App.css';

export default () => {
  return (
    <h1 className={style.title}>
      Hello World
    </h1>
  );
};

In above codes, we import a CSS module from App.css into a style object, and use style.title to represent a class name.

.title {
  color: red;
}

The build runner will compile the class name style.title into a hash string.

<h1 class="_3zyde4l1yATCOkgn-DBWEL">
  Hello World
</h1>

And App.css is also compiled.

._3zyde4l1yATCOkgn-DBWEL {
  color: red;
}

Now this class name becomes unique and only effective to the App component.

CSS Modules provides plugins for different build runners. This repo uses css-loader for Webpack, since it support CSS Modules best and is easy to use. By the way, if you don't know Webpack, please read my tutorial Webpack-Demos.

The following is our webpack.config.js.

module.exports = {
  entry: __dirname + '/index.js',
  output: {
    publicPath: '/',
    filename: './bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel',
        query: {
          presets: ['es2015', 'stage-0', 'react']
        }
      },
      {
        test: /\.css$/,
        loader: "style-loader!css-loader?modules"
      },
    ]
  }
};

The magic line is loader: "style-loader!css-loader?modules", which appends the query parameter modules after css-loader enabling the CSS Modules feature.

Now run the demo.

$ npm run demo01

Open http://localhost:8080, you should see the h1 in red.

Demo02: Global Scope

demo / sources

The syntax :global(.className) could be used to declare a global selector explicitly. CSS Modules will not compile this class name into hash string.

First, add a global class into App.css.

.title {
  color: red;
}

:global(.title) {
  color: green;
}

Then use the global CSS class in App.js.

import React from 'react';
import styles from './App.css';

export default () => {
  return (
    <h1 className="title">
      Hello World
    </h1>
  );
};

Run the demo.

$ npm run demo02

Open http://localhost:8080, you should see the h1 title in green.

CSS Modules also has a explicit local scope syntax :local(.className) which is equivalent to .className. So the above App.css could be written in another form.

:local(.title) {
  color: red;
}

:global(.title) {
  color: green;
}

Demo03: Customized Hash Class Name

demo / sources

CSS-loader's default hash algorithm is [hash:base64], which compiles.title into something like ._3zyde4l1yATCOkgn-DBWEL.

You could customize it in webpack.config.js.

module: {
  loaders: [
    // ...
    {
      test: /\.css$/,
      loader: "style-loader!css-loader?modules&localIdentName=[path][name]---[local]---[hash:base64:5]"
    },
  ]
}

Run the demo.

$ npm run demo03

You will find .title hashed into demo03-components-App---title---GpMto.

Demo04: Composing CSS Classes

demo / sources

In CSS Modules, a selector could inherit another selector's rules, which is called "composition".

We let .title inherit .className in App.css.

.className {
  background-color: blue;
}

.title {
  composes: className;
  color: red;
}

App.js is the same.

import React from 'react';
import style from './App.css';

export default () => {
  return (
    <h1 className={style.title}>
      Hello World
    </h1>
  );
};

Run the demo.

$ npm run demo04

You should see a red h1 title in a blue background.

After the building process, App.css is converted into the following codes.

._2DHwuiHWMnKTOYG45T0x34 {
  color: red;
}

._10B-buq6_BEOTOl9urIjf8 {
  background-color: blue;
}

And the HTML element h1's class names should look like <h1 class="_2DHwuiHWMnKTOYG45T0x34 _10B-buq6_BEOTOl9urIjf8">,

Demo05: Import Other Modules

demo / sources

You also could inherit rules from another CSS file.

another.css

.className {
  background-color: blue;
}

App.css

.title {
  composes: className from './another.css';
  color: red;
}

Run the demo.

$ npm run demo05

You should see a red h1 title in a blue background.

Demo06: Exporting Values Variables

demo / sources

You could use variables in CSS Modules. This feature is provided by PostCSS and the postcss-modules-values plugin.

$ npm install --save postcss-loader postcss-modules-values

Add postcss-loader into webpack.config.js.

var values = require('postcss-modules-values');

module.exports = {
  entry: __dirname + '/index.js',
  output: {
    publicPath: '/',
    filename: './bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel',
        query: {
          presets: ['es2015', 'stage-0', 'react']
        }
      },
      {
        test: /\.css$/,
        loader: "style-loader!css-loader?modules!postcss-loader"
      },
    ]
  },
  postcss: [
    values
  ]
};

Next, set up your values/variables in colors.css.

@value blue: #0c77f8;
@value red: #ff0000;
@value green: #aaf200;

Then import them into App.css.

@value colors: "./colors.css";
@value blue, red, green from colors;

.title {
  color: red;
  background-color: blue;
}

Run the demo.

$ npm run demo06

License

MIT

More Repositories

1

weekly

科技爱好者周刊,每周五发布
33,058
star
2

es6tutorial

《ECMAScript 6入门》是一本开源的 JavaScript 语言教程,全面介绍 ECMAScript 6 新增的语法特性。
JavaScript
20,881
star
3

jstraining

全栈工程师培训材料
18,959
star
4

react-demos

a collection of simple demos of React.js
JavaScript
16,171
star
5

free-books

互联网上的免费书籍
13,692
star
6

document-style-guide

中文技术文档的写作规范
10,968
star
7

webpack-demos

a collection of simple demos of Webpack
JavaScript
9,588
star
8

jstutorial

Javascript tutorial book
CSS
5,421
star
9

simple-bash-scripts

A collection of simple Bash scripts
Shell
1,415
star
10

reading-list

Some books I read
1,309
star
11

react-babel-webpack-boilerplate

a boilerplate for React-Babel-Webpack project
JavaScript
1,154
star
12

articles

personal articles
921
star
13

loppo

an extremely easy static site generator of markdown documents
JavaScript
707
star
14

wechat-miniprogram-demos

微信小程序教程库
599
star
15

book-computer-networks

Free E-Book: Computer Networks - A Systems Approach
596
star
16

koa-demos

A collection of simple demos of Koa
485
star
17

extremely-simple-flux-demo

Learn Flux from an extremely simple demo
JavaScript
442
star
18

fortunes

A collection of fortune database files for Chinese users.
335
star
19

survivor

博客文集《未来世界的幸存者》
CSS
325
star
20

chrome-extension-demo

how to create a Chrome extension
JavaScript
302
star
21

node-oauth-demo

A very simple demo of OAuth2.0 using node.js
JavaScript
301
star
22

mocha-demos

a collection of simple demos of Mocha
JavaScript
254
star
23

tiny-browser-require

A tiny, simple CommonJS require() implemetation in browser-side
JavaScript
237
star
24

react-testing-demo

A tutorial of testing React components
JavaScript
214
star
25

road

博客文集《前方的路》
CSS
150
star
26

sina-news

新浪全球实时新闻
JavaScript
133
star
27

github-actions-demo

a demo of GitHub actions for a simple React App
JavaScript
132
star
28

weather-action

An example of GitHub Actions
Shell
107
star
29

user-tracking-demos

demos of tracking users with JavaScript
JavaScript
90
star
30

travis-ci-demo

A beginner tutorial of Travis CI for Node projects
75
star
31

openrecord-demos

an ORM tutorial for nodejs
73
star
32

website

HTML
63
star
33

markdown-it-image-lazy-loading

a markdown-it plugin supporting Chrome 75's native image lazy-loading
JavaScript
54
star
34

flux-todomvc-demo

A simplified version of Flux's official TodoMVC demo
CSS
49
star
35

Google-Calendar-Lite

A single-page webapp of Google Calendar, based on its API.
CSS
41
star
36

nilka

a command-line utility to resize images in batches
JavaScript
39
star
37

webpack-static-site-demo

a demo of generating a static site with React, React-Router, and Webpack
JavaScript
32
star
38

turpan

a wrapped markdown renderer based on markdown-it
JavaScript
27
star
39

hn

A personalized Hacker News
JavaScript
26
star
40

rpio-led-demo

controlling an LED with Raspberry Pi's GPIO
JavaScript
25
star
41

koa-simple-server

A simple koa server demo of logging HTTP request Headers and body
JavaScript
25
star
42

jekyll_demo

A very simple demo of Jekyll
22
star
43

node-systemd-demo

run a Node app as a daemon with Systemd
JavaScript
20
star
44

lvv2-feed

Lvv2.com's RSS feed
JavaScript
16
star
45

blog-stylesheet

my blog's stylesheet
CSS
14
star
46

loppo-theme-oceandeep

the default theme of Loppo
JavaScript
13
star
47

tarim

a template engine, using Lodash's template syntax and supporting including other templates
JavaScript
13
star
48

loppo-theme-ryf

个人网站的 Loppo 主题
CSS
11
star
49

Formula-Online-Generator

using Google Chart api to generate mathematical formulas in a webpage
10
star
50

turpan-remove-space

remove the space between English word and Chinese characters in markdown files
JavaScript
9
star
51

eslint-plugin-ignoreuglify

exclude uglified files from ESLint's linting
JavaScript
3
star
52

slides

JavaScript
3
star