Gulp 增量式无间断构建

jm81lzqq  于 2022-12-08  发布在  Gulp
关注(0)|答案(3)|浏览(167)

在我的办公室里,我们正在使用gulp来构建我们的less文件。我想改进构建任务,因为它花了一秒钟的时间来构建我们最近工作的一个大项目。我的想法是缓存文件,只传递改变的文件。所以我从google开始,发现javascript的增量构建,我认为重写它们更容易。下面是我开始的一个:https://github.com/gulpjs/gulp/blob/master/docs/recipes/incremental-builds-with-concatenate.md
经过几次不成功的尝试后,我得到了以下代码(用最新的bootstrap发行版测试):

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);
        }
    });
});

但这只传递了更改过的文件,less编译器因为缺少变量定义而失败。如果我在less任务之前使用concat插件,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:我计划在以后添加掉毛,源Map,缩小,evtl。缓存破坏和自动前缀。

5lhxktic

5lhxktic1#

和Ashwell一样,我发现使用导入来确保我所有的LESS文件都能访问它们所需要的变量和mixin是很有用的。我还使用LESS文件来绑定导入。这有几个优点:
1.我可以利用LESS的特性来做一些复杂的事情,比如覆盖变量值以生成多个主题,或者在另一个LESS文件中的每个规则前面添加一个类。
1.不需要concat插件。
1.像WebEssentials for Visual Studio这样的工具可以给予语法帮助和输出预览,因为每个LESS文件都完全能够自己呈现。
如果您想导入变量、mixin等,但又不想实际输出另一个文件的全部内容,可以用途:

@import (reference) "_colors.less";

经过几天的努力,我终于能够得到一个增量构建,它可以正确地重建依赖于我修改的LESS文件的所有对象。我记录了结果here。这是最终的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's 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's 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's run when you run "gulp" without any arguments.
gulp.task('default', ['less']);

我们现在可以简单地运行gulp live来构建所有LESS文件,然后允许每个后续更改只构建依赖于更改文件的那些文件。

ycl3bljg

ycl3bljg2#

因此,当我想在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 ))作为runCompile函数的参数dest
编辑:我刚刚意识到这可能解决不了你的“变量丢失”问题。我没有任何东西来解决这个问题,因为我组织我的LESS文件时大量使用导入,所以每个需要一组变量的文件都有一个导入语句来确保它们在那里。

puruo6ea

puruo6ea3#

实际上,我们可以使用gulp-newergulp-subgenerate-mtime来完成这个任务。Stripling的方法几乎是最好的一种方法,每次运行gulp less任务时,它都会从头开始编译所有内容,然后开始查看文件。如果您使用的样式表较少,这将花费您大量的时间。gulp-subgenerate-mtime类似于gulp-subgenerate除了它做真正的核心的东西。每次一个文件通过gulp-subgenerate-mtime,它检查导入中的任何修改,如果是,它将调整流中当前文件的mtime,使其通过gulp-newer。我觉得这更好,因为我们甚至没有缓存任何东西。

//Compile less for deployment 
   gulp.task("less", () => {
      return gulp
        .src(["static/less/**/*.less"])
        .pipe(progenyMtime())
        .pipe(
          plumber({
            errorHandler: function (err) {
              log(chalk.bgRed.white.bold(err.message));
            },
          })
        )
        .pipe(filter(["**/*.less", "!**/_*.less", "!static/less/includes*/**"]))
        .pipe(newer({ dest: "static/css/", ext: ".css" }))
        .pipe(debug({ title: "LESS" }))
        .pipe(
          less({
            plugins: [cleanCss, autoprefix],
          })
        )
        .pipe(gulp.dest("static/css/"));
    });

    //Watch changes is less and compile if changed.
    gulp.task("watch-less", () => {
      return gulp.watch("static/less/**/*.less", gulp.series("less"));
    });
    
    //Compile all less files on first run ( if changed ) then compile only modified files from next run
    gulp.task("live-less", gulp.series("less", "watch-less"));

相关问题