# postcss

# Goals

使用 postcss 的目的:

  1. 使用 scss;
  2. 使用 sourcemap
  3. 自动添加浏览器前缀:autoprefixer;
  4. 兼容 ie8

# gulpfile.js

var gulp = require('gulp'); //gulp
var sass = require('gulp-sass'); //gulp-sass
var postcss = require('gulp-postcss'); //gulp-postcss
var sourcemaps = require('gulp-sourcemaps'); //sourcemaps
var autoprefixer = require('autoprefixer'); //自动添加浏览器前缀
var mqpacker = require('css-mqpacker'); //合并media query
var cssnano = require('cssnano'); //css优化压缩
var color_rgba_fallback = require('postcss-color-rgba-fallback'); //给rgba()颜色创建降级方案
var opacity = require('postcss-opacity'); //给opacity提供降级方案
var pseudoelements = require('postcss-pseudoelements'); //将伪元素的::转换为:
var vmin = require('postcss-vmin'); //使用vm为vmin做降级处理
var pixrem = require('pixrem'); //给rem添加px作为降级处理
var will_change = require('postcss-will-change'); //为will-change动画属性添加回退

//新建任务scss
gulp.task('scss', function() {
  //设置postcss处理插件
  var processors = [
    will_change,
    autoprefixer,
    color_rgba_fallback,
    opacity,
    pseudoelements,
    vmin,
    pixrem,
    autoprefixer({ browsers: ['last 4 versions', '> 0.2%', 'ie>=8'] }),
    mqpacker,
    // cssnano,//dev不用压缩
  ];
  //指定需要处理的.scss文件目录
  return gulp
    .src('./scss/*.scss')
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError)) //要放在postcss之前
    .pipe(postcss(processors))
    .pipe(sourcemaps.write('./')) //指定.css.map文件生成目录
    .pipe(gulp.dest('./dest')); //指定处理之后生成的css文件目录
});

//新建任务scss:watch 监控.scss文件的变化自动处理
gulp.task('scss:watch', function() {
  gulp.watch('./scss/*.scss', ['scss']);
});

//设置默认任务并指定依赖任务scss:watch
gulp.task('default', ['scss:watch']);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

# HowToUseIt

  1. mkdir 'myfolder' then cd 'myfolder';
  2. copy devDependencies and gulpfile.js;
  3. npm install /cnpm install;
  4. write your .scss files;
  5. CLI: gulp ,run gulp;

# devDependencies

  "devDependencies": {
    "autoprefixer": "^7.2.3",
    "gulp": "^3.9.0",
    "gulp-postcss": "^6.0.0",
    "gulp-sass": "^3.1.0",
    "gulp-sourcemaps": "^2.6.1",
    "pixrem": "^4.0.1",
    "postcss-color-rgba-fallback": "^3.0.0",
    "postcss-opacity": "^5.0.0",
    "postcss-pseudoelements": "^5.0.0",
    "postcss-vmin": "^3.0.0",
    "postcss-will-change": "^2.0.0"
  }
1
2
3
4
5
6
7
8
9
10
11
12
13

# references

  1. using-postcss-for-cross-browser-compatibility (opens new window)
  2. getting-started-with-postcss-a-quick-guide-for-sass-users (opens new window)
  3. using-postcss-together-with-sass-stylus-or-less (opens new window)
  4. postcss-deep-dive-roll-your-own-preprocessor (opens new window)
Last Updated: 2/8/2023, 2:30:06 AM