解决问题:css是公共的,不同文件加载的css最终的呈现方式都是在同一个文件中出现,会导致样式覆盖。css-modules的解决思路是:生成hash类名,具有唯一性。
引用方法:通过打包工具引入,如webpack。
以下以react为例:
.babelrc
{
"presets": [
["env", {
"targets": {
"browsers": [ "> 1%","last 2 versions", "safari >= 7","not ie <= 10"]
},
"useBuiltIns": true
}],
"react",
"stage-0"
],
"plugins": [
["import", { "libraryName": "antd", "style": true }],
]
}
package.json
{
"name": "css-modules",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack --watch",
"debug": "cross-env NODE_ENV=development:test node --inspect-brk node_modules/webpack/bin/webpack.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.26.3",
"babel-loader": "7",
"babel-plugin-import": "^1.12.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"cross-env": "^5.2.0",
"css-loader": "^3.1.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"style-loader": "^0.23.1",
"webpack": "^4.36.1",
"webpack-cli": "^3.3.6"
}
}
webpack.config.js
const path = require('path');
module.exports = {
entry: './index.js',
output: {
path: path.resolve(__dirname,'./'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {
modules: true,
// camelCase: 'dashes'
// localIdentName: '[path][name]__[local]--[hash:base64:5]' //不可用??不知道啥情况
},
}
]
}
]
}
}
css-loader配置--参考:https://www.webpackjs.com/loaders/css-loader/#%E9%80%89%E9%A1%B9
最终效果: