下载
// postcss 的命令行工具
// sudo cnpm install -g postcss-cli
// 先安装一下需要的库
npm install postcss --save
// autoprefixer 插件
npm install autoprefixer --save
// precss 插件
npm install precss --save
配置
在vue-loader.config.js中,加入 autoprefixer 的配置
module.exports = {
loaders: utils.cssLoaders({
sourceMap: sourceMapEnabled,
extract: isProduction
}),
// postcss插件配置
postcss: [
require('autoprefixer')// 前缀
],
cssSourceMap: sourceMapEnabled,
cacheBusting: config.dev.cacheBusting,
transformToRequire: {
video: ['src', 'poster'],
source: 'src',
img: 'src',
image: 'xlink:href'
}
};
使用
eg1
vue 组件中 css 如下:
<style scoped>
.test {
display: flex;
transition: all linear 1s;
}
</style>
编译后将自动添加前缀
.test {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-transition: all linear 1s;
transition: all linear 1s;
}
eg2
// postcss-js.js 封装
// 请先npm install 相关包
import postcss from 'postcss' // postcss
import postcssJs from 'postcss-js' // css
import autoprefixer from 'autoprefixer' // 自动前缀
import nested from 'postcss-nested' // 嵌套语法
import variables from 'postcss-css-variables' // 支持变量 如:root{--a:#333}
function processCssJs(cssJs) {
return postcss([autoprefixer, nested, variables]).process(
cssJs, {parser: postcssJs}).css
}
export default processCssJs
import processCssJs from './postcss';
let cssJs ={
":root"{
--c:#fff
}
"#id1": {
"backgrounColor": var(--c),
"&:hover": {
"backgrounColor": "#eee"
}
}
}
processCssJs(cssJs)
// 渲染出的结果
#id1{
backgroun-color:#fff
}
#id1:hover{
backgroun-color:#eee
}
参考文档
官方文档
https://github.com/postcss/postcss
https://github.com/postcss/postcss-cli
讲解
推荐:https://wiki.zhuzi.me/docs/build_temp/2027
推荐:https://segmentfault.com/a/1190000003909268
PostCSS 是个什么? https://segmentfault.com/a/1190000003909268
vue中使用postcss:https://juejin.im/post/581bfc368ac247004fe174af