Gulp sass编译只更改了已更改文件的文件夹

时间:2017-07-20 13:13:40

标签: css sass gulp gulp-sass

已经有人提出了很多关于这方面的问题,但不幸的是,他们都没有解决我的问题......

在办公室,我们有一个自定义的PHP框架和一些在流浪盒中运行它的应用程序。 关于SCSS文件,很久以前就定义了一条规则。它们位于“scss”文件夹中并在../中编译(大多数情况下是 css 文件夹)。我们使用npm和 gulp-sass 来执行此操作,使用 gulp-autoprefixer

示例:foo / bar / css / scss /foo.scss - >富/酒吧/的 CSS /foo.css

问题是在我们的框架中,我们没有一个共同的“dest”文件夹,所以手表当前就是这样:

framework/**/scss/**/*.scss

我们在框架中有多个子模块,以及 scss 文件夹的多个可能路径,例如:

  • FW /子模块/ _www / CSS /富/酒吧/ SCSS /
  • FW /子模块/ subsubmodule / _www / CSS /富/酒吧/ fooagain / SCSS /
  • FW /子模块/视图/ TPL /库/库名称/默认/ CSS /富/酒吧/ SCSS /

等...

所以为了在正确的地方编译,我们使用gulp-rename(文件夹var是FW的名称)在祖先文件夹中编译。

gulp.task('sass', () => {
    return gulp.src([folder+'**/scss/**/*.scss'])
        .pipe(plumber())
        .pipe(sass(sassOptions))
        .pipe(autoprefixer(autoprefixerOptions))
        .pipe(rename((filePath) => {
            filePath.dirname = filePath.dirname.replace("scss", "");
        })).pipe(gulp.dest(folder));
});

问题是:当你保存scss文件时,它会编译~200文件。这个。是。所以。长。

完整编译需要8到20秒。

在我们的预生产服务器中,我们有一个bash,可以在保存时运行并编译所有兄弟scss文件。但是我没有用gulp做到这一点。

我的愿望是:scss文件被更改,我们编译他和他的兄弟姐妹。不是每个scss文件。你认为有可能吗?

非常感谢。

3 个答案:

答案 0 :(得分:0)

你可以在gulpfile中创建一个功能,为每个"组提供特定的任务" scss文件。 像这样的东西

function compileStylesTask(taskName, srcFiles, distFolder, compiledFileName) {
    gulp.task(taskName, function () {
        var style = gulp.src(srcFiles)
            .pipe(sass().on('error', sass.logError))
            .pipe(rename({basename: compiledFileName}))
            .pipe(gulp.dest(distFolder))
        return merge(style);
    });
}

compileStylesTask('someCustomCssTask', [
    'src/css/some.scss',
    'src/css/some2.scss'
], 'someCompiledName', '/dist/css');

在您的观看任务中,您现在可以像这样单独为每个组添加手表

gulp.task('watch', function () {
    gulp.watch('/src/scss/some.scss', ['someCustomCssTask']);
});

这将仅触发此特定scss任务运行。

答案 1 :(得分:0)

  

如果有什么东西踢他,可以通过Google翻译成英文))

事实证明只编译了修改过的文件!

输出结果为:

file.scss
 - file.css
 - file.min.css
 - file.min.css.map

它无法击败Watcher,他会在启动“oneSassFileCompile”功能后立即创建文件,只有在Watcher停止后才会创建文件。

退出情况 - 启动助手任务。 但是再次没有找到如何传递参数。 我不得不求助于一个外部变量,我希望它不会导致许多文件立即更改,并且此变量无法跳过所有文件。

抱歉我的英文。 对于我的剧本,我第一次写信给NodeJS,第一次遇到Gulp!

如果最终将参数直接抛入子任务中,或者甚至更好地强制在Watcher中调用函数时立即创建文件,我将很高兴看到解决方案!

  

标签:gulp sass只监视一个文件更改并编译css   autoprefixer缩小并映射

gulpfile.js code:

/**
 * Variables
 */
var gulp        = require('gulp'),
    argv        = require('yargs').argv,
    sass        = require('gulp-sass'),
    rename      = require('gulp-rename'),
    //cssmin      = require('gulp-cssnano'), - a very long initialization, because of what is not convenient for a constant launch, but on the watcher will probably rise norms
    cleanCSS    = require('gulp-clean-css'),
    prefix      = require('gulp-autoprefixer'),
    plumber     = require('gulp-plumber'),
    notify      = require('gulp-notify'),
    sassLint    = require('gulp-sass-lint'),
    sourcemaps  = require('gulp-sourcemaps');

// Temporary solution until gulp 4
// https://github.com/gulpjs/gulp/issues/355
var runSequence = require('run-sequence');

/**
 * Settings
 */
var sassProjectPath = 'templates/**/*.scss';
var sassOptions     = {
    outputStyle: 'expanded'
};
var prefixerOptions = {
    browsers: ['last 5 versions'],
    cascade: true
};


/**
 * Secondary functions
 */
var displayError = function(error) {
    // Initial building up of the error
    var errorString = '[' + error.plugin.error.bold + ']';
    errorString += ' ' + error.message.replace("\n",''); // Removes new line at the end

    // If the error contains the filename or line number add it to the string
    if(error.fileName)
        errorString += ' in ' + error.fileName;

    if(error.lineNumber)
        errorString += ' on line ' + error.lineNumber.bold;

    // This will output an error like the following:
    // [gulp-sass] error message in file_name on line 1
    console.error(errorString);
};
var onError      = function(err) {
    notify.onError({
        title:    "Gulp",
        subtitle: "Failure!",
        message:  "Error: <%= error.message %>",
        sound:    "Basso"
    })(err);
    this.emit('end');
};


// BUILD SUB-TASKS
// ---------------


/**
 * Compiling a single single SASS file
 */
var oneSassFileCompile = function(filePath, destinationDir){
    var fullFileName, fileName, baseDir;

    // Checking the parameters
    if(!filePath) {
        console.log('param filePath miss');
        return false;
    }

    // Find file paths
    fullFileName    = filePath.replace(/\\/g,'/').replace(/.*\//, '');
    fileName        = fullFileName.replace('.'+ fullFileName.split('.').pop(), '');
    baseDir         = filePath.replace(fullFileName, '');

    // If you do not specify a folder to save, use the current
    destinationDir         = destinationDir || baseDir;

    // Compile
    return gulp.src(filePath)
        // Error Handler
        .pipe(plumber({errorHandler: onError}))
        // For generic style.css.map
        .pipe(sourcemaps.init())
        // The actual compilation
        .pipe(sass(sassOptions))
        // Adding Manufacturer Prefixes
        .pipe(prefix(prefixerOptions))
        // Call the file
        .pipe(rename(fileName +'.css'))
        // Save the compiled version
        .pipe(gulp.dest(destinationDir))

        // Compress CSS
        //.pipe(cssmin())
        .pipe(cleanCSS())
        // Rename the suffix
        .pipe(rename({suffix: '.min'}))
        // Save the .map
        .pipe(sourcemaps.write('./'))
        // Save the compressed file
        .pipe(gulp.dest(destinationDir));
};

/**
 * Task to start compiling a specific file
 * For PHPStorm File Watcher
 */
gulp.task('sass-file', function() {
    var filePath        = argv.filePath,
        destinationDir  = argv.destDir;

    // Checking the parameters
    if(!filePath) {
        console.log('argv --filePath miss');
        return false;
    }
    return oneSassFileCompile(filePath, destinationDir)
});


/**
 * Compiling all SASS project files
 * TODO - customize the paths and check
 */
gulp.task('sass-project', function() {
    return gulp.src(sassProjectPath)
        .pipe(plumber({errorHandler: onError}))
        .pipe(sourcemaps.init())
        .pipe(sass(sassOptions))
        .pipe(prefix(prefixerOptions))
        .pipe(rename(fileName +'.css'))
        .pipe(gulp.dest('./'))

        // Compress CSS
        //.pipe(cssmin())
        .pipe(cleanCSS())
        .pipe(rename({suffix: '.min'}))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('./'));
});


/**
 * Task checks the SASS project files
 * TODO - customize the paths and check
 */
gulp.task('sass-lint', function() {
    gulp.src(sassProjectPath)
        .pipe(sassLint())
        .pipe(sassLint.format())
        .pipe(sassLint.failOnError());
});


/**
 * Watcher for all SASS project files
 */
// An auxiliary variable to transfer the file path from the watcher to the task
var sassWatchFilePath = '';
gulp.task('sass-watch', function() {
    gulp.watch(sassProjectPath, function(watchEvent){
        console.log('Watcher catch: '+ watchEvent.type +' :: '+ watchEvent.path);

        // Skip deleting
        if(watchEvent.type === 'deleted')
            return;

        // We set the variable with the path and start the helper
        sassWatchFilePath = watchEvent.path;
        gulp.start('sass-watch-helper');
    });
});
/*
 * Taks helper, if you immediately call "oneSassFileCompile" in sass-watch,
  * then the files are not created until the process ends. watcher = (
 */
gulp.task('sass-watch-helper', function() {
    var tmpPath = sassWatchFilePath;
    sassWatchFilePath = null;
    // Compilation
    return oneSassFileCompile(tmpPath);
});


// BUILD TASKS
// ------------


/**
 * Default task
 */
gulp.task('default', function(done) {
    runSequence('sass-project', 'sass-watch', done);
});

/**
 * Project Collector
 */
gulp.task('build', function(done) {
    runSequence('sass-project', done);
});

答案 2 :(得分:0)

您可能需要gulp-changedgulp-cached来过滤为您更改的文件。

所以您的情况应该是

const cached = require('gulp-cached');
gulp.task('sass', () => {
return gulp.src([folder+'**/scss/**/*.scss'])
    .pipe(cached('cached files')) // this will exclude the file that haven't changed
    .pipe(plumber())
    .pipe(sass(sassOptions))
    .pipe(autoprefixer(autoprefixerOptions))
    .pipe(rename((filePath) => {
        filePath.dirname = filePath.dirname.replace("scss", "");
    })).pipe(gulp.dest(folder));
});
相关问题