# postcss
# Goals
使用 postcss 的目的:
- 使用 scss;
- 使用 sourcemap
- 自动添加浏览器前缀:autoprefixer;
- 兼容 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
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
- mkdir 'myfolder' then cd 'myfolder';
- copy devDependencies and gulpfile.js;
- npm install /cnpm install;
- write your .scss files;
- 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
2
3
4
5
6
7
8
9
10
11
12
13