1. 程式人生 > 實用技巧 >webpack4 css modules

webpack4 css modules

準備工作

安裝webpack:

npm init -y
npm i -D webpack webpack-cli css-loader

建立 webpack.config.js進行配置:

const path = require('path');
const MinicssExtractPlugin = require('mini-css-extract-plugin');
const htmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: {
    main: './src/index.js
' }, module: { rules: [ // 不在 node_modules 中的 css,開啟 css modules { test: /\.css$/, exclude: /node_modules/, use: [ MiniCssExtractPlugin.loader, { loader: 'css-loader', options: { /* 以前版本是通過 true 開啟,相關配置接著寫 modules: true localIdentName: '[name]__[local]--[hash:base64:5]' */ // 現在是給 modules 一個 options 物件開啟 modules: { // 重新生成的 css 類名 localIdentName: '[name]__[local]--[hash:base64:5]' } } } ] }, // 在 node_modules 中的 css,不開啟 { test: /\.css$/, include: /node_modules/, use: [ MiniCssExtractPlugin.loader, 'css-loader'] } ] }, plugins: [ new HtmlWebpackPlugin({ template: path.resolve(__dirname, './src/index.html'), filename: 'index.html' }), new MiniCssExtractPlugin({ filename: '[name].[hash].css' }) ], output: { filename: '[name].[hash].bundle.js', path: path.resolve(__dirname, './dist') } }

更多 css-loader 的配置建議前往github_css-loader檢視,因為版本更新後,配置可能會有變。

編寫 css

配置完 webpack,寫 css 時要使用相關語法,因為是通過 webpack 打包時進行編譯,重新生成新的 css 類名來防止全域性變數名汙染的。

注意: css modules 只針對類、Id選擇器生效,不會對標籤選擇器進行模組化。

/* 全域性樣式 */
:global(.header) {
  color: #696969;
  background-color: #fff;
}

:global .main {
  color: #363636;
  background-color: #fff;
}

/* less 等預處理語言可以這樣寫 */
/* :global {
  .footer {
    color: #303030;
    background-color: #fff;
  }
} */


/* 區域性樣式 */
:local(.header) {
  color: red;
  background-color: #c2b1b1;
}

:local(.main) {
  color: yellow;
  background-color: rgb(136, 96, 96);
}

:local(.footer) {
  color: blue;
  background-color: #929292;
}

編譯後的 css程式碼:

/* 全域性樣式 */
.header {
  color: #696969;
  background-color: #fff;
}

.main {
  color: #363636;
  background-color: #fff;
}

/* less 等預處理語言可以這樣寫 */
/* :global {
  .footer {
    color: #303030;
    background-color: #fff;
  }
} */


/* 區域性樣式 */
.index__header--1JD7j {
  color: red;
  background-color: #c2b1b1;
}

.index__main--1j9-Y {
  color: yellow;
  background-color: rgb(136, 96, 96);
}

.index__footer--gJKjp {
  color: blue;
  background-color: #929292;
}

電腦刺繡繡花廠 http://www.szhdn.com 廣州品牌設計公司https://www.houdianzi.com

使用

因為 css 類名是重新編譯後的,所以使用時不能直接使用原 css 類名,要通過 import語法使用。

import styles from './index.css';

export const Header = () => {
  return `
    <h1 class=${styles.header}>header</h1>
  `
}

在 html 裡面是這樣的:

<h1 class="index__header--1JD7j">header</h1>