本文主要讲述了:
- 作用
- 安装
- 示例
- 配置
正文
作用
postcss-preset-env允许开发者使用最新的CSS语法而不用担心浏览器兼容性。postcss-preset-env会将最新的CSS语法转换为目标环境的浏览器能够理解的CSS语法。
安装
今天在配置postcss-loader,使用autoprefixer发现根本没有用。 postcss.config.js中是这样的: module.exports = { plugins:[ require('autoprefixer') ] } 然后打包也没报错,只是没有起任何作用,一些需要加前缀的地方毫无变化。没作用岂不是白配了。然后我又去搜索如何解决autoprefixer失效问题,发现还需要配置兼容的浏览器。我又按照方法在postcss.config.js中配置。 module.exports = { plugins:[ require('autoprefixer')({ "browsers": [ "defaults", "not ie < 8", "last 2 versions", "> 1%", "iOS 7", "last 3 iOS versions" ] }) ] } 这里兼容浏览器的版本可以自己设置。 然后打包,结果成功,该添加的前缀都添加了。但是却有一段警告:
虽然不影响结果,可这红的黄的提示对我们程序员来说十分不友好呀,所以我一定要干掉它。我用我蹩脚的英语理解了一下大概意思,就是使用 browserslist去替换browsers。browserslist不是添加在postcss.config.js中,而是添加在package.json中。这样做是为了避免browsers可能会导致的错误。所以要想完美解决,就需要这样: postcss.config.js module.exports = { plugins:[ require('autoprefixer') ] } package.json "browserslist": [ "defaults", "not ie < 8", "last 2 versions", "> 1%", "iOS 7", "last 3 iOS versions" ], 这段加在author,keywords同一级
|
示例
learn_postcss/postcss.config.js
1 2 3 4 5 | module.exports = { plugins: { "postcss-preset-env": {} } }; |
源文件:
learn_postcss/index.css
1 2 3 4 5 6 7 8 | :root { --mainColor: #12345678; } body { color: var(--mainColor); display: flex; } |
编译:
1 | npx postcss index.css --output index.compiled.css |
输出:learn_postcss/index.compiled.css
1 2 3 4 5 6 7 8 9 | :root { --mainColor: rgba(18,52,86,0.47059); } body { color: rgba(18,52,86,0.47059); color: var(--mainColor); display: flex; } |
配置
注意:在没有任何配置的情况下,postcss-preset-env会开启stage 2阶段的特性并支持所有浏览器。
stage
此属性决定了哪些CSS特性需要被填充。
stage共分为5个阶段,分别是:
- stage-0 非官方草案
- stage-1 编辑草案或早期工作草案
- stage-2 工作草案
- stage-3 候选版本
- stage-4 推荐标准
示例:
1 2 3 4 5 6 7 | module.exports = { plugins: { "postcss-preset-env": { stage: 0 } } }; |
features
此属性决定了哪些特性应该被开启或者关闭。
browsers
postcss-preset-env使用browserslist来配置目标环境。
autoprefixer
postcss-preset-env集成了autoprefixer。