Подтвердить что ты не робот

Инкрементный gulp меньше сборки

В моем офисе мы используем gulp для сборки наших меньших файлов. Я хотел бы улучшить задачу сборки, поскольку потребовалось больше времени, чтобы построить крупный проект, над которым мы недавно работали. Идея заключалась в том, чтобы кэшировать файлы и передавать только те, которые были изменены. Итак, я начал с google и нашел инкрементные сборки для javascript ang, и было бы легко переписать их за меньшее. Здесь я начал с: https://github.com/gulpjs/gulp/blob/master/docs/recipes/incremental-builds-with-concatenate.md

После нескольких неудачных попыток я закончил с кодом (тестировался с последним дистрибутивом бутстрапа):

var gulp            = require('gulp');
var less            = require('gulp-less');
var concat          = require('gulp-concat');
var remember        = require('gulp-remember');
var cached          = require('gulp-cached');

var fileGlob = [
    './bootstrap/**/*.less',
    '!./bootstrap/bootstrap.less',
    '!./bootstrap/mixins.less'
];

gulp.task('less', function () {
    return gulp.src(fileGlob)
        .pipe(cached('lessFiles'))
        .pipe(remember('lessFiles'))
        .pipe(less())
        .pipe(gulp.dest('output'));
});

gulp.task('watch', function () {
    var watcher = gulp.watch(fileGlob, ['less']);
    watcher.on('change', function (e) {
        if (e.type === 'deleted') {
            delete cached.caches.scripts[e.path];
            remember.forget('lessFiles', e.path);
        }
    });
});

Но это передает только измененный файл, а компилятор меньше, из-за отсутствия определений переменных. Если я подключаю конкат-плагин до меньшей задачи, gulp застревает в бесконечном цикле (по-видимому).

gulp.task('less', function () {
    return gulp.src(fileGlob)
        .pipe(cached('lessFiles'))
        .pipe(remember('lessFiles'))
        .pipe(concat('main.less')
        .pipe(less())
        .pipe(gulp.dest('output'));
});

Есть ли у кого-нибудь опыт работы с этими плагинами или ему удалось создать инкрементную меньшую сборку другим способом. Вот (беспорядочный) репозиторий github для тестирования: https://github.com/tuelsch/perfect-less-build

PS: Я планирую добавить linting, sourcemaps, minification, evtl. кэширование и автоопределитель позже.

4b9b3361

Ответ 1

Как и Ashwell, я нашел полезным использовать импорт, чтобы гарантировать, что все мои файлы LESS имеют доступ к переменным и миксинам, которые им нужны. Я также использую файл LESS с импортом для комплектации. Это имеет несколько преимуществ:

  • Я могу использовать функции LESS для выполнения сложных задач, таких как переопределение значений переменных для создания нескольких тем или добавление класса к каждому правилу в другом файле LESS.
  • Нет необходимости в плагине concat.
  • Инструменты, такие как Web Essentials для Visual Studio, могут предоставлять синтаксическую справку и предварительный просмотр вывода, потому что каждый LESS файл полностью способен отображать сам по себе.

Если вы хотите импортировать переменные, mixins и т.д., но вы не хотите выводить все содержимое другого файла, вы можете использовать:

@import (reference) "_colors.less";

После нескольких дней усилий я наконец смог получить инкрементную сборку, которая правильно перестраивает все объекты, зависящие от файла LESS, который я изменил. Я документировал результаты здесь. Это последний файл gulpfile:

/*
 * This file defines how our static resources get built.
 * From the StaticCommon root folder, call "gulp" to compile all generated
 * client-side resources, or call "gulp watch" to keep checking source 
 * files, and rebuild them whenever they are changed. Call "gulp live" to 
 * do both (build and watch).
 */

/* Dependency definitions: in order to avoid forcing everyone to have 
 * node/npm installed on their systems, we are including all of the 
 * necessary dependencies in the node_modules folder. To install new ones,
 * you must install nodejs on your machine, and use the "npm install XXX" 
 * command. */
var gulp = require('gulp');
var less = require('gulp-less');
var LessPluginCleanCss = require('less-plugin-clean-css'),
    cleanCss = new LessPluginCleanCss();
var sourcemaps = require('gulp-sourcemaps');
var rename = require('gulp-rename');
var cache = require('gulp-cached');
var progeny = require('gulp-progeny');
var filter = require('gulp-filter');
var plumber = require('gulp-plumber');
var debug = require('gulp-debug');

gulp.task('less', function() {
    return gulp
        // Even though some of our LESS files are just references, and 
        // aren't built, we need to start by looking at all of them because 
        // if any of them change, we may need to rebuild other less files.
        .src(
        ['Content/@(Theme|Areas|Css)/**/*.less'],
        { base: 'Content' })
        // This makes it so that errors are output to the console rather 
        // than silently crashing the app.
        .pipe(plumber({
            errorHandler: function (err) {
                console.log(err);
                // And this makes it so "watch" can continue after an error.
                this.emit('end');
            }
        }))
        // When running in "watch" mode, the contents of these files will 
        // be kept in an in-memory cache, and after the initial hit, we'll
        // only rebuild when file contents change.
        .pipe(cache('less'))
        // This will build a dependency tree based on any @import 
        // statements found by the given REGEX. If you change one file,
        // we'll rebuild any other files that reference it.
        .pipe(progeny({
            regexp: /^\s*@import\s*(?:\(\w+\)\s*)?['"]([^'"]+)['"]/
        }))
        // Now that we've set up the dependency tree, we can filter out 
        // any files whose
        // file names start with an underscore (_)
        .pipe(filter(['**/*.less', '!**/_*.less']))
        // This will output the name of each LESS file that we're about 
        // to rebuild.
        .pipe(debug({ title: 'LESS' }))
        // This starts capturing the line-numbers as we transform these 
        // files, allowing us to output a source map for each LESS file 
        // in the final stages.
        // Browsers like Chrome can pick up those source maps and show you 
        // the actual LESS source line that a given rule came from, 
        // despite the source file being transformed and minified.
        .pipe(sourcemaps.init())
        // Run the transformation from LESS to CSS
        .pipe(less({
            // Minify the CSS to get rid of extra space and most CSS
            // comments.
            plugins: [cleanCss]
        }))
        // We need a reliable way to indicate that the file was built
        // with gulp, so we can ignore it in Mercurial commits.
        // Lots of css libraries get distributed as .min.css files, so
        // we don't want to exclude that pattern. Let try .opt.css 
        // instead.
        .pipe(rename(function(path) {
            path.extname = ".opt.css";
        }))
        // Now that we've captured all of our sourcemap mappings, add
        // the source map comment at the bottom of each minified CSS 
        // file, and output the *.css.map file to the same folder as 
        // the original file.
        .pipe(sourcemaps.write('.'))
        // Write all these generated files back to the Content folder.
        .pipe(gulp.dest('Content'));
});

// Keep an eye on any LESS files, and if they change then invoke the 
// 'less' task.
gulp.task('watch', function() {
    return gulp.watch('Content/@(Theme|Areas|Css)/**/*.less', ['less']);
});

// Build things first, then keep a watch on any changed files.
gulp.task('live', ['less', 'watch']);

// This is the task that run when you run "gulp" without any arguments.
gulp.task('default', ['less']);

Теперь мы можем просто запустить gulp live для создания всех наших файлов LESS один раз, а затем разрешить каждому последующему изменению просто создавать файлы, зависящие от измененных файлов.

Ответ 2

Поэтому, когда я хочу делать инкрементные сборки в gulp, я делаю это, абстрагируя внутренний процесс задачи gulp, поэтому мне не нужно беспокоиться о сохранении кеша.

// Create a function that does just the processing
var runCompile = function( src, dest, opts ){
  return gulp.src( src )
    .pipe(less( opts ))
    .pipe(gulp.dest( dest ));
};

// Leverage the function to create the task
gulp.task( 'less', function(){
  return runCompile( fileGlob, 'output', {} );
});

// Use it again in the watch task
gulp.task( 'less:watch', function(){
  return gulp.watch( fileGlob )
    .on( "change", function( event ){
      // might need to play with the dest dir here
      return runCompile( event.path, 'output', {} );
    });
});

Это отлично работает для меня, и я использую этот шаблон во всех своих задачах gulp. Однако я заметил, что когда-нибудь gulp будет раздавать дорожки во время просмотра "on change", если он получает один файл. В этом случае я делаю манипуляцию с моими мыслями, что-то вроде path.dirname(srcPath.replace( srcDir, outputDir )) как аргумент dest для функции runCompile.

Изменить: просто понял, что это, вероятно, не решит вашу проблему с потерянными переменными. У меня нет ничего от моей головы, чтобы решить эту проблему, поскольку я организовываю файлы LESS с интенсивным использованием импорта, поэтому для каждого файла, который будет нужен набор переменных, будет иметь оператор импорта, гарантирующий, что они есть.