前端开发你一定要了解的——PostCSS
What——什么是PostCSS
一个使用JavaScript转换CSS来实现我们所需要的改变的工具。
How——PostCSS如何工作的
Vite自身已支持PostCSS,仅需在vite.config.ts中配置,或根目录创建postcss.config.js文件进行相应配置。
PostCSS类似于一个中间件,在其中可以引入不同作用的插件,达到不同的效果来辅助开发,后面会举例几个插件的用途和用法。
Why——为什么要使用PostCSS
- 自动补全兼容性CSS,解决老旧浏览器的兼容问题。
- 可以放心书写各类新特性,新属性。
- 模块化CSS,支持各种mixin混合、嵌套和插入方式。
- 支持自定义插件,可自己编写自己想要的插件。
How——如何使用PostCSS
此处以Vite构建的项目为例
根目录下创建 postcss.config.js
文件
export default {
plugins: {
tailwindcss: {},
autoprefixer: {
//css兼容前缀
overrideBrowserslist: [
'Android 4.1',
'ios 7.1',
'Chrome >31',
'not ie <=11', //不考虑IE浏览器
'ff >= 30', //仅新版本用'ff >= 30
'>1%', //全球统计有超过1%的使用了使用'> 1%'
'last 2 version' //所有主流浏览器最近2个版本
],
grid: true //开启grid布局的兼容(浏览器IE除外其它都能兼容grid,可以关闭开启)
},
'postcss-import': {},
cssnano: {},
'postcss-preset-env': {
/* use stage 3 features + css nesting rules */
stage: 3,
features: {
'nesting-rules': true
}
}
}
}
其中包含的所有插件,均需使用 npm install -D xxxx
安装对应依赖。
推荐插件
tailwindcss(强烈推荐)
一个工具集,包含了大量类似 flex
、 pt-4
、 text-center
以及 rotate-90
等工具类,可以组合使用并直接在 HTML 代码上实现任何 UI 设计。
// tailwind.config.js
/** @type {import('tailwindcss').Config} */
export default {
content: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'],
theme: {
colors: {
transparent: 'transparent',
blue: '#0874FF',
'blue-dark': '#173e67',
white: '#fff',
'gray-light': '#f0f2f6',
gray: '#cfdee5',
red: '#ED3A3A',
yellow: '#F9CA04'
},
extend: {
spacing: {
'8xl': '96rem',
'9xl': '128rem'
},
borderRadius: {
'4xl': '2rem'
}
}
},
plugins: []
}
postcss-import
当在CSS中 import
多个其它的CSS文件时, postcss-import
插件会将所有 import
编译到最后一个文件,提升性能效率。
Autoprefixer
自动补全各类兼容性CSS,例如 -webkit-
、-ms-
等等。
export default {
plugins: {
autoprefixer: {
//css兼容前缀
overrideBrowserslist: [
'Android 4.1',
'ios 7.1',
'Chrome >31',
'not ie <=11', //不考虑IE浏览器
'ff >= 30', //仅新版本用'ff >= 30
'>1%', //全球统计有超过1%的使用了使用'> 1%'
'last 2 version' //所有主流浏览器最近2个版本
],
grid: true //开启grid布局的兼容(浏览器IE除外其它都能兼容grid,可以关闭开启)
},
}
}
CSSNano
自动优化压缩CSS。
postcss-mixin
赋予CSS中编写mixin混合的能力(类似SASS)。
postcss-nested
赋予CSS中嵌套书写的能力(类似LESS和SASS)。
postcss-preset-env
自动改写CSS为旧浏览器也可识别的格式。
评论区