PostCSS核心功能配置
PostCSS是一个用JavaScript工具和插件转换CSS代码的工具。
PostCSS是一个工具容器,本身不具备转换CSS的功能,必须利用其他工具和插件来完成CSS代码的转换。
1. PostCSS功能一览
1. 配合Autoprefixer添加CSS兼容性前缀;
2. 将新一代的语法转换成浏览器能够解析的语法;
3. 解决CSS命名冲突的问题;
4. 配合stylellint检查CSS代码中的错误;
5. 配合LostGrid利用calc()创建网格系统;
2. postcss-loader
postcss-loader,Postcss加载器,配置加载并处理postcss功能的loader。
a. sugarss
sugarss提供类sass语法支持,配置后可以使用缩进式,嵌套的写法。
.container
width: 300px
height: 300px
background-color: red
transition: container 1s
b. autoprefixer
autoprefixer是postcss配置中比较常用的插件。
可以为CSS添加兼容性前缀。autoprefixer存在以下配置。
plugins: [
require('autoprefixer')({
overrideBrowserslist: [
// 全球超过1%的人正在使用的浏览器
// '> 1%',
// 在美国大于5%使用覆盖率的浏览器
// '> 5% in US'
// 所有浏览器兼容到最后5个版本 可以生效 标准 -> CanIUse.com
'last 5 versions'
// 火狐浏览器的最新版本
// 'Firefox ESR'
// 指定火狐浏览器的版本范围大于20
// 'Firefox > 20'
// 指定火狐浏览器的版本12.1 可以生效
// 'Firefox 12'
// 所有浏览器的BETA测试版
// 'unreleased versions'
// 指定chrome浏览器的测试版本
// 'unreleased Chrome versions'
// 2012年之后发布的所有浏览器及版本 可以生效
// 'since 2012'
]
})
如果不使用其它插件,也可以这样简化配置。
plugins () {
return [autoprefixer('last 5 versions')];
}
c. precss
支持类sass、less的样式预处理的语法特性。
如果不使用sass、less时,可以使用这种方式配置。
plugins () {
require('precss')
}
$whValue: 400px;
.container {
width: $whValue;
height: $whValue;
}
d. cssnano
cssnano,用于优化css源码。
plugins () {
require('cssnano')()
}
CSS代码优化前:
.container {
width: calc(100 * 3px);
height: 300px;
background-color: red;
transition: container 1s;
}
CSS代码优化后:
.container{width:300px;height:300px;background-color:red;transition:container 1s}
e. sytlelint
用于检查CSS代码的书写规范。依赖 stylelint-config-standard(stylelint检查配置标准)。
sytlelint 配置比较繁琐,可以安装 stylelint-config-standard 标准配置。
根目录下创建 .stylelintrc 文件。
{
"extends": "stylelint-config-standard"
}
可以在webpack.config.js文件追加忽略哪些检查。
plugins () {
require('stylelint')({
rules: {
'declaration-colon-space-after': 'never'
}
})
}
f. postcss-import
对import的样式表文件进行合并处理,与press的功能重复(预处理),可以关闭press。
plugins () {
require('postcss-import')()
}
CSS源码优化前:
@import './common.css' (min-width: 1000px);
CSS源码优化后:
@media (min-width: 1000px) {
html {
background-color: orange;
}
}
g. postcss-cssnext
使用最新的css语法(包括草案)、包含autoprefixer。使用不是很多。
个人感觉CSS3之后的发展感觉还是比较困难的,现有的开发模式已经固化。
除非推出具有颠覆性的特性,才会让大部分企业可能使用最新的CSS语法。
目前使用sass-loader和less-loader已经能满足日常的开发需求。
plugins () {
require('postcss-cssnext')()
}
:root {
--redColor: red;
--wh: {
width: 300px;
height: 300px;
}
}
.container {
@apply --wh;
background-color: var(--redColor);
transition: container 1s;
}
3. 总结
文章总结了PostCSS核心功能的相关配置,后面会继续深入学习webpack,加油 💪。