使用webpack构建模块化css

基础

webpack配置

{
    test: /\.css$/i,
    use: [
      "style-loader",
      {
        loader: "css-loader",
        options: {
          modules: true,
          sourceMap: true
        }
      }
    ]
}

MyComponent.css

:local(.foo) {
  color: red;
}
:local(.bar) {
  color: blue;
}
:local(.r) {
  border-radius: 50%;
}

h1 {
  color: red;
}

使用

import styles from "~src/MyComponent.css";
import Img from "~assets/image.jpg";

const img = document.querySelector<HTMLImageElement>("img");
if (img) {
  img.src = Img;
  img.classList.add(styles.r);
}

打包后

<style>
    ._3TZ96BmTtVNv-BOgb2aFzo {
      color: red;
    }
    ._3gvygpszZcxJRjo6V0346I {
      color: blue;
    }
    ._4rJVJ7iRMI6zJ77kftpH7 {
      border-radius: 50%;
    }
    
    h1 {
      color: red;
    }
</style>

<img src="b51677ea5ce239f26c593c119279f2c6.jpg" class="_4rJVJ7iRMI6zJ77kftpH7">

简写

和上面的效果一样,应为modules: true默认为Local

.foo {
  color: red;
}
.bar {
  color: blue;
}
.r {
  border-radius: 50%;
}

h1 {
  color: red;
}

自定义标识符 详情 loader-utils

我这里只演示一个简单的

webpack.config.js

  {
    test: /\.css$/i,
    use: [
      "style-loader",
      {
        loader: "css-loader",
        options: {
          modules: {
            mode: "local",
            localIdentName: "[local]--[hash:base64:3]"
          }
        }
      }
    ]
  }

打包后:

<style>
    .foo--3TZ {
      color: red;
    }
    .bar--3gv {
      color: blue;
    }
    .r--4rJ {
      border-radius: 50%;
    }
    
    h1 {
      color: red;
    }
</style>

<img src="b51677ea5ce239f26c593c119279f2c6.jpg" class="r--4rJ">

自定义

webpack.config.js

const loaderUtils = require("loader-utils");

  {
    test: /\.css$/i,
    use: [
      "style-loader",
      {
        loader: "css-loader",
        options: {
          modules: {
            mode: "local",
            hashPrefix: "[hash:base64:3]",
            getLocalIdent: (
              context,
              localIdentName,
              localName,
              options
            ) => {
              const hash = loaderUtils.interpolateName(
                context,
                `__${options.hashPrefix}`,
                { content: localName }
              );
              return `${localName}[_prop]`;
            }
          }
        }
      }
    ]
  }

index.ts

import "~src/MyComponent.css";
import Img from "~assets/image.jpg";

const img = document.querySelector<HTMLImageElement>("img");
if (img) {
  img.src = Img;
  img.classList.add("r");
  img.setAttribute("_prop", "");
}

打包后:

<style>
    .foo[_prop] {
      color: red;
    }
    .bar[_prop] {
      color: blue;
    }
    .r[_prop] {
      border-radius: 50%;
    }
    
    h1 {
      color: red;
    }
</style>

<img src="b51677ea5ce239f26c593c119279f2c6.jpg" class="r" _prop="">
posted @ 2020-01-16 10:54  Ajanuw  阅读(2)  评论(0编辑  收藏  举报