摘自
http://ju.outofmemory.cn/entry/215105
http://www.w3cplus.com/PostCSS/postcss-deep-dive-preprocessing-with-precss.htmljavascript
官方定義
「PostCSS is a tool for transforming CSS with JS plugins. These plugins can support variables and mixins, transpile future CSS syntax, inline images, and more.css
PostCss是一個能夠運行在Gulp Grunt Webpack中的插件
同時它又是一套CSS處理插件的一個環境html
基本和Sass同樣 要和Sass那樣使用變量java
/*PostCSS是一個Gulp插件 同時是一套Css插件的運行環境*/ /*PostCSS和Sass語法最爲類似 PostCSS將Sass那樣的表達形式直接寫在css文件中*/ .menu1 { width: 100%; a { text-decoration: none; } &::before { content: ''; } } /*使用PreCSS插件(PostCSS中的插件)來作變量 條件處理*/ /*PreCSS is a tool that allows you to use Sass-like markup in your CSS files. Enjoy a familiar syntax with variables, mixins, conditionals, and other goodies. */ /*LESS中使用@符聲明變量,好比@color: #ccc; Stylus中使用$符聲明變量,好比$color=#ccc; Sass中使用$符聲明變量,好比$color: #ccc;*/ $text_color: #232323; $blue: #056ef0; $column: 200px; body { color: $text_color; } .menu { width: calc(4 * $column); } .menu_link { background: $blue; width: $column; } /*條件*/ /*和Sass同樣 判斷表達式兩邊要有空格 不然不識別表達式*/ $column_layout: 2; .column { @if $column_layout == 2 { width: 50%; float: left; } @else { width: 100%; } } /*循環*/ .for-test { @for $i from 1 to 3 { p:nth-of-type($i) { margin-left: calc( 100% / $i); } } } /*each循環在循環體中不是 $icon 而是 $(icon) */ .each-test { @each $icon in (foo, bar, baz) { .icon-$(icon) { background: url('icons/$(icon).png'); } } } /*包含mixin*/ /*@define-mixin 規則名 變量名*/ @define-mixin icon $name { padding-left: 16px; &::after { content: ""; background-url: url(/icons/$(name).png); } } .search { @mixin icon search; } .search2{ @mixin icon search2; } /*擴展*/ @define-extend bg-green { background: green; } .notice--clear { @extend bg-green; } .xx-clear{ @extend bg-green; } /*擴展會減小冗餘 獲得的結果以下*/ /*.notice--clear, .xx-clear { background: green; }*/ /*值的複製*/ /*最後獲得 margin: 20px;padding: 20px;*/ .heading { margin: 20px; padding: @margin; }
var gulp = require('gulp'); var postcss = require('gulp-postcss'); var sourcemaps = require('gulp-sourcemaps'); gulp.task('css', function() { return gulp.src('src/*.css') .pipe(sourcemaps.init()) .pipe(postcss([require('autoprefixer'), require('precss')])) //.pipe(postcss([ autoprefixer({ browsers: ['last 2 versions'] }) ])) .pipe(sourcemaps.write('.')) .pipe(gulp.dest('build/')); }); gulp.task('watch',function() { gulp.watch('src/*.css', ['css']); }); gulp.task('default', ['css','watch']);
注意,webpack對css的各個資源引用都有檢查,好比背景圖片不存在的話,會有Errorwebpack
var webpack = require('webpack'); var path = require('path'); module.exports = { entry: path.join(__dirname, 'main.js'), output: { path: path.join(__dirname, 'out'), publicPath: "./out/", filename: 'bundle.js' }, module: { loaders: [{ test: /\.css$/, loader: "style-loader!css-loader!postcss-loader" }] }, postcss: function() { return [require('autoprefixer'), require('precss')]; } }
PS
main.js和style.css在同一個文件夾中
在main.js中須要引入這個css文件才行var css = require('./style.css');
web