1、安装style.loader和css.loader:
cnpm i style-loader css-loader -D
2、在webpack中配置css loader:
{
test: /\.css$/,
use: ["style-loader", "css-loader"] //打包处理css样式表的第三方loader
}
整个webpack.config.js文件内容如下:
const path = require("path")
const htmlWebpackPlugin = require("html-webpack-plugin") // 导入 在内存中自动生成html文件 的插件
// 创建一个插件的实例对象
const htmlPlugin = new htmlWebpackPlugin({
template: path.join(__dirname, "./src/index.html"), // 源文件
filename: "index.html" // 生成的 内存中首页的 名称
})
// 向外暴露一个打包的实例对象,因为webpack是基于Node构建的,所以webpack支持所有Node API和语法
// webpack 默认只能打包处理.js后缀名类型的文件,想.vue .png无法主动处理,所以要配置第三方的loader
module.exports = {
mode: 'development', // development 或 production
plugins: [
htmlPlugin
],
module: { // 所有第三方模块的配置规则
rules: [ // 第三方匹配规则
{
test: /\.js|jsx$/,
use: "babel-loader",
exclude: /node_modules/ // exclude千万别忘记
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"] //打包处理css样式表的第三方loader
}
]
},
resolve: {
extensions: [".js", ".jsx", ".json"],
alias: {
"@": path.join(__dirname, "./src") // 这样@符号就表示项目根目录中src这一层路径
}
}
}
3、新建css文件:
style.css文件内容如下:
.title{
fonts-size: 16px;
color: #ff0000;
}
4、组件中引入css文件并在“className”属性名后添加相关css类名:
import React from 'react'
// 直接导入css样式表默认是在全局上,整个项目上生效的,且会存在冲突
import '@/css/style.css'
class Person extends React.Component {
constructor(){
super()
}
render(){
return (
{this.state.msg}
)
}
}
export default Person
直接导入css样式会存在样式冲突的问题,如何解决?
1、在webpack的css-loader后添加一个modules参数,表示为普通的css样式表启用模块化。
{
test: /\.css$/,
use: ["style-loader", "css-loader?modules"] // modules参数表示为普通的css样式表启用模块化
}
2、修改className中内容的传递方式:
import styleObj from '@/css/style.css'
{this.state.msg}
import React from 'react'
// 直接导入css样式表默认是在全局上,整个项目上生效的,且会存在冲突
import styleObj from '@/css/style.css'
class Person extends React.Component {
constructor(){
super()
}
render(){
return (
{this.state.msg}
)
}
}
export default Person
其中的style.css内容注意事项:
.title{
fonts-size: 16px;
color: #ff0000;
}
/* css模块化 只针对类选择器和id选择器生效 */
/* css模块化 不会将标签选择器模块化 */
/*h1{
font-style: italic;
}*/
#box{
font-size: 16px;
}
使用localIdentName来自定义模块化的类名:
在webpack.config.js配置文件中的css-loader中使用localIdentName如下:
rules: [ // 第三方匹配规则
{
test: /\.js|jsx$/,
use: "babel-loader",
exclude: /node_modules/ // exclude千万别忘记
},
{
test: /\.css$/,
use: [
{loader: "style-loader"},
{loader: "css-loader",
options: {
modules: {
localIdentName: "[path][name]-[local]-[hash:5]"
}
}
}], //打包处理css样式表的第三方loader
}
]
注意:使用这样的方式配置会报错
rules: [ // 第三方匹配规则
{
test: /\.js|jsx$/,
use: "babel-loader",
exclude: /node_modules/ // exclude千万别忘记
},
{
test: /\.css$/,
use: ["style-loader", "css-loader?modules&localIdentName=[path][name]-[local]-[hash:5]"] //打包处理css样式表的第三方loader,modules参数表示为普通的css样式表启用模块化
}
]
通过local和global设置类名是否被模块化:
使用:local()和:global():
1、:local()包裹的类名,是被模块化的类名,只能通过className={cssObj.类名}来使用,同时:local()默认可不写,这样在样式表中定义的类名都是被模块化的类名;
2、:global()包裹的类名,是全局生效的,不会被css-modules控制,定义的类名是什么,就是使用定义的类名className="类名";
3、标签选择器不会被模块化控制。