2017-03-02 26 views
0

我正在开发一个轻量级的WordPress主题,我想使用所需的style.css文件作为我唯一的CSS文件。如何使用gulp-sass生成有效的缩小WP style.css文件?

我的要求是:

  1. 它必须有WordPress的stylesheet header,它
  2. 和CSS代码应该精缩。

我使用SASS,我用gulp-sass来编译它。现在,我在做:

/* gulpfile.babel.js */ 

const base = { 
    src: 'src', 
    dest: 'my-theme' 
}; 

const routes = { 
    sass: { 
     src: `${base.src}/scss/style.scss`, 
     dest: `${base.dest}/` 
    } 
}; 

gulp.task('styles',() => { 
    return gulp.src(routes.sass.src) 
    .pipe(plumber((err) => { 
     console.error(err.message); 
    })) 
    .pipe(sass()) 
    .pipe(autoprefixer()) 
    .pipe(gulp.dest(routes.sass.dest)); 
}); 

而且我style.scss包含:

/* 
Theme Name: My Theme Name 
Theme URI: http://example.com/my-theme 
Author: My name 
Author URI: http://example.com/ 
Description: My theme description 
Version: 1.0 
License: GNU General Public License v3 or later 
License URI: http://www.gnu.org/licenses/gpl-3.0.html 
Tags: custom, lightweight 
Text Domain: textdomain 

This theme, like WordPress, is licensed under the GPL. 
Use it to make something cool, have fun, and share what you've learned with others. 
*/ 
@import 'common'; 

这工作,但它不适合我的第二个要求(精缩CSS)。如果我添加

.pipe(sass({outputStyle: 'compressed'})) 

然后我失去标题。我无法在gulp-sassnode-sass上找到任何选项,以缩小&保留/* … */的评论。

有没有人想出了解决方案?

回答

1

不要使用compress选项来缩小你的CSS。改为使用gulp-cssnano插件。无论如何它都更好,它支持discardComments选项,您可以设置为false以保留评论:

var cssnano = require('gulp-cssnano'); 

gulp.task('styles',() => { 
    return gulp.src(routes.sass.src) 
    .pipe(plumber((err) => { 
     console.error(err.message); 
    })) 
    .pipe(sass()) 
    .pipe(autoprefixer()) 
    .pipe(cssnano({discardComments:false})) 
    .pipe(gulp.dest(routes.sass.dest)); 
}); 
1

我的建议是你可以使用gulp-concat和run-sequence来达到你的要求。您可以将标题分隔为另一个文件,等待sass任务完成,并将它和头文件一起连接。

var gulp = require('gulp'); 
var runSequence = require('run-sequence'); 
var concat = require('gulp-concat'); 

/** 
* Gulp task to run your current styles and 
* the task to append the header in sequence 
*/ 
gulp.task('stylesWithHeader', function(callback) { 
    runSequence('styles', 'prepend-header', callback); 
}); 

/** 
* Gulp task to generate the styles.css file with theme header 
*/ 
gulp.task('prepend-header', function(callback) { 
    return gulp.src([HEADER_FILE.txt, COMPILED_STYLES_WITHOUT_HEADER.css]) 
     .pipe(concat("styles.css")) 
     .pipe(gulp.dest(PATH_TO_YOUR_TEMPLATE)) 
     ; 
}); 

咕嘟咕嘟CONCAT:https://www.npmjs.com/package/gulp-concat

咕嘟咕嘟运行顺序:https://www.npmjs.com/package/run-sequence

相关问题