css modules need to use webpack packaging tools to achieve this. The idea is that the file can be imported css js module, and an object is introduced. Js then be used in the properties of this object class name as html element, webpack plug-in will eventually css selectors and js Lane with a unique string instead of the class name, so the css properties will only It was introduced to the html js css file generated. js css modules required to generate all html. The following is a simple example of the css modules:
|
|
composes the keyword class can refer to a style other classes:
|
|
使用css modules
在一个新文件夹下初始化一个npm项目:
|
|
安装webpack:
|
|
新建一个webpack配置文件webpack.config.js:
|
|
上面的entry和path要写绝对路径,html-webpack-plugin用于自动生成index.html。
要在项目中使用es6语法,需要安装下面的npm模块:
|
|
在webpack.config.js中加上loader:
|
|
处理css需要使用css-loader和style-loader:
|
|
添加一个index.css:
|
|
index.js:
|
|
注意在index.js中给元素添加class名时不是直接用css中的选择器(text),而是用对象的属性(style.text)。
并更改配置文件:
|
|
css-loader后面加了一个查询参数modules,表示打开 CSS Modules 功能。
运行index.html后,打开devtool,可以看到div的class名为_3e3Tpl6iY2cwXJCwpTZ4dc
,这是由webpack的loader自动生成的。并且head中多了一个style标签:
|
|
上面的内联style是style-loader生成的,为了生成一个独立的css文件,可使用:
|
|
原文:大专栏 初探css modules