天天看点

webpack项目初始配置(二)——css modules与antd

在react项目中,直接引入样式文件会影响到全局样式,并非独立的。

解决方法有五种:

1、行内样式(react官网推荐)

class App extends React.Component {
  // ...
  render() {
    return (
      <div style={{ background: '#eee', width: '200px', height: '200px'}}>
        <p style= {{color:'red', fontSize:'40px'}}>行内样式</p>
      </div>
    )
  }
}
           

2、声明样式

class App extends React.Component {

//...

 const style1={    
      background:'#eee',
      width:'200px',
      height:'200px'
    }

  const style2={    
      color:'red',
      fontSize:'40px'
    }

  render() {
    return (
      <div style={style1}>
        <p style= {style2}>行内样式</p>
      </div>
    )
  }
}
           

3、开启css modules功能

相关教程:

作者:阮一峰

链接(css modules用法教程):http://www.ruanyifeng.com/blog/2016/06/css_modules.html

4、利用第三方工具Styled Components

具体使用在此不详述。

个人推荐第一种方法与第三种方法,即行内样式与css modules结合的方式。下面接着上一章的《webpack项目初始配置(一)》中的内容,配置webpack.config.js文件,因为新手爬坑过程中,很容易遇到开启了css modules功能之后,antd默认的样式就不生效的问题。

//css的处理,开启css modules功能,node_modules库中的antd样式除外
	  {
	  	test: /\.css$/,
	    exclude: /node_modules|antd\.css/,
	  	use: ExtractTextPlugin.extract({
	  		fallback:'style-loader',
			use: "css-loader?modules&localIdentName=styles__[local]__[hash:base64:5]"
	  	}),
	  },
     //css的处理,node_modules库中的antd样式不开启css modules功能,但还是要编译的
	  {
	  	test: /\.css$/,
	    include: /node_modules|antd\.css/,
	  	use: ExtractTextPlugin.extract({
	  		fallback:'style-loader',
	  		use: "css-loader"
	  	})
	  },
		//这里开启自己编写的less文件的css modules功能,除了node_modules库中的less
		//也就是可以过滤掉antd库中的样式
		{
          test: /\.less$/,
		  exclude: /node_modules/,
          use: ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: ["css-loader?modules&localIdentName=styles__[local]__[hash:base64:5]",
			  {
			  	loader: 'less-loader', options: {modifyVars: theme}
			  }
		  ]
        })
      },
		//less的处理,需要加入node_modules里面的样式,并且不开启css modules功能
		{
          test: /\.less$/,
          include: /node_modules/,
          use: ExtractTextPlugin.extract({
			  fallback: "style-loader",
			  use: ["css-loader",
				  {
					loader: 'less-loader', options: {modifyVars: theme}
				  }
			  ]
          })
        },
           

关键代码说明:

//开启css modules之前的代码

use: "css-loader"

//开启css modules之后的代码

use: "css-loader?modules&localIdentName=styles__[local]__[hash:base64:5]

//     ?modules  是开启css_modules

//     localIdentName定义哈希字符串的格式

效果:

引入样式:

webpack项目初始配置(二)——css modules与antd

定义样式index.less:

webpack项目初始配置(二)——css modules与antd

网页编译后:

webpack项目初始配置(二)——css modules与antd