programing

Gulp 태스크를 순차적으로 실행하는 방법

procenter 2022. 9. 21. 22:35
반응형

Gulp 태스크를 순차적으로 실행하는 방법

다음과 같은 스니펫을 참조해 주세요.

gulp.task "coffee", ->
    gulp.src("src/server/**/*.coffee")
        .pipe(coffee {bare: true}).on("error",gutil.log)
        .pipe(gulp.dest "bin")

gulp.task "clean",->
    gulp.src("bin", {read:false})
        .pipe clean
            force:true

gulp.task 'develop',['clean','coffee'], ->
    console.log "run something else"

»develop하고 clean'달리다'를 한다.coffee이치노릇을 하다이 부품은 작동하지 않습니다.언언부부 부다다다다다

기본적으로 gulp은 명시적으로 종속되지 않는 한 태스크를 동시에 실행합니다., 하다, 하다, 하다, 하다, 이런 별로 이 되지 않습니다.clean의지하고 싶지는 않지만 무엇보다 먼저 도망쳐야 하는 곳이죠.

이 문제를 단숨에 해결하기 위해 특별히 플러그인을 작성했습니다.인스톨 후에는, 다음과 같이 사용합니다.

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

gulp.task('develop', function(done) {
    runSequence('clean', 'coffee', function() {
        console.log('Run something else');
        done();
    });
});

패키지 README의 전체 지침을 읽을 수 있습니다. 또한 일부 태스크 세트를 동시에 실행할 수도 있습니다.

이는 다음 주요 Gulp 릴리스에서 (효과적으로) 수정될 것입니다.이는 자동 의존성 순서를 완전히 없애고run-sequence원하는 실행 순서를 수동으로 지정할 수 있습니다.

은 큰에 굳이 run-sequence 오늘.

이 문제에 대한 적절한 해결책은 gulp 매뉴얼에 기재되어 있습니다.

var gulp = require('gulp');

// takes in a callback so the engine knows when it'll be done
gulp.task('one', function(cb) {
  // do stuff -- async or otherwise
  cb(err); // if err is not null and not undefined, the orchestration will stop, and 'two' will not run
});

// identifies a dependent task must be complete before this one begins
gulp.task('two', ['one'], function() {
  // task 'one' is done now
});

gulp.task('default', ['one', 'two']);
// alternatively: gulp.task('default', ['two']);

아직 정식 릴리스는 아니지만, 곧 출시될 Gulp 4.0을 통해 gulp.series로 동기 작업을 쉽게 수행할 수 있습니다.다음과 같이 간단하게 할 수 있습니다.

gulp.task('develop', gulp.series('clean', 'coffee'))

업그레이드와 사용법을 소개하는 좋은 블로그 투고를 찾았습니다.를 들어 gulp 4로 이행하는 것입니다.

generator-gulp-webapp Yeoman generator를 이용하여 node/gulp 앱을 생성하였습니다.「깨끗한 난제」는, 다음과 같이 처리했습니다(질문에 기재된 원래의 태스크로 변환됩니다).

gulp.task('develop', ['clean'], function () {
  gulp.start('coffee');
});

실행 시퀀스가 가장 명확한 방법입니다(최소한 Gulp 4.0이 출시될 때까지).

실행 시퀀스를 사용하면 작업은 다음과 같습니다.

var sequence = require('run-sequence');
/* ... */
gulp.task('develop', function (done) {
    sequence('clean', 'coffee', done);
});

그러나 (어떤 이유로) 사용하지 않으려는 경우 방법이 도움이 됩니다.

gulp.task('develop', ['clean'], function (done) {
    gulp.on('task_stop', function (event) {
        if (event.task === 'coffee') {
            done();
        }
    });
    gulp.start('coffee');
});

주의: , " "는 " " "developcoffee혼란스러울 수 있습니다.

필요하지 않은 경우 이벤트 청취자를 제거할 수도 있습니다.

gulp.task('develop', ['clean'], function (done) {
    function onFinish(event) {
        if (event.task === 'coffee') {
            gulp.removeListener('task_stop', onFinish);
            done();
        }
    }
    gulp.on('task_stop', onFinish);
    gulp.start('coffee');
});

듣고 싶은 이벤트도 있다고 생각합니다. task_stop했을 때 는 반면, 에는 성공했을 때 트리거됩니다.task_err에러가 발생했을 때 표시됩니다.

왜 ,, 왜, 왜, 왜, 왜, 왜, 왜, document, document, 습, 습, you, you, you, you, you, you, you, you, you, you, you, you, you, you, yougulp.start()이은 '꿀꺽 삼키다' 입니다.

gulp.start은 빌드 수 있기 때문에 되어 있지 않습니다. 사용자가 파일을 사용하지 있습니다.

(출처 : https://github.com/gulpjs/gulp/issues/426#issuecomment-41208007)

Gulp 문서에 따르면:

의존관계가 완료되기 전에 작업이 실행되고 있습니까?의존관계 태스크가 비동기 실행 힌트를 올바르게 사용하고 있는지 확인합니다.콜백을 받아들이거나 약속 또는 이벤트스트림을 반환합니다.

작업 시퀀스를 동기화하여 실행하려면

  1. 스트림을 " " " " " " " " " ( " 。gulp.src부터 )까지gulp.task스트림이 언제 종료되는지 작업을 알립니다.
  2. 합니다.gulp.task.

개정된 코드를 참조하십시오.

gulp.task "coffee", ->
    return gulp.src("src/server/**/*.coffee")
        .pipe(coffee {bare: true}).on("error",gutil.log)
        .pipe(gulp.dest "bin")

gulp.task "clean", ['coffee'], ->
      return gulp.src("bin", {read:false})
        .pipe clean
            force:true

gulp.task 'develop',['clean','coffee'], ->
    console.log "run something else"

저도 똑같은 문제를 겪고 있었는데 해결이 꽤 쉬웠어요.기본적으로 코드를 다음과 같이 변경하면 작동합니다.메모: gulp.src 이전 반환은 나에게 큰 차이를 가져왔다.

gulp.task "coffee", ->
    return gulp.src("src/server/**/*.coffee")
        .pipe(coffee {bare: true}).on("error",gutil.log)
        .pipe(gulp.dest "bin")

gulp.task "clean",->
    return gulp.src("bin", {read:false})
        .pipe clean
            force:true

gulp.task 'develop',['clean','coffee'], ->
    console.log "run something else"

제안된 해결책을 모두 시도해 보았지만 모두 나름의 문제가 있는 것 같습니다.

소스, Orchestrator 소스를 .start()구현에서는 마지막 파라미터가 함수일 경우 콜백으로 처리됨을 알 수 있습니다.

이 단편은 제가 맡은 일을 위해 쓴 것입니다.

  gulp.task( 'task1', () => console.log(a) )
  gulp.task( 'task2', () => console.log(a) )
  gulp.task( 'task3', () => console.log(a) )
  gulp.task( 'task4', () => console.log(a) )
  gulp.task( 'task5', () => console.log(a) )

  function runSequential( tasks ) {
    if( !tasks || tasks.length <= 0 ) return;

    const task = tasks[0];
    gulp.start( task, () => {
        console.log( `${task} finished` );
        runSequential( tasks.slice(1) );
    } );
  }
  gulp.task( "run-all", () => runSequential([ "task1", "task2", "task3", "task4", "task5" ));

나는 이 답을 한동안 찾고 있었다.이제 공식 삼키기 문서에서 찾았어요.

마지막 작업이 완료되었을 때 gulp 작업을 수행하려면 스트림을 반환해야 합니다.

gulp.task('wiredep', ['dev-jade'], function () {
    var stream = gulp.src(paths.output + '*.html')
        .pipe($.wiredep())
        .pipe(gulp.dest(paths.output));

    return stream; // execute next task when this is completed
});

// First will execute and complete wiredep task
gulp.task('prod-jade', ['wiredep'], function() {
    gulp.src(paths.output + '**/*.html')
        .pipe($.minifyHtml())
        .pipe(gulp.dest(paths.output));
});

★★★★★★★★★★★★★★★★★★★★★★★coffee 의존하다clean , , , , 입니다.develop 의존하다coffee:

gulp.task('coffee', ['clean'], function(){...});
gulp.task('develop', ['coffee'], function(){...});

.★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★」cleancoffeedevelop해 주세요.clean의 및 coffee실장에서는 콜백을 받아들일 필요가 있습니다.그 때문에, 엔진은 콜백을 실시하는 타이밍을 알 수 있습니다.

gulp.task('clean', function(callback){
  del(['dist/*'], callback);
});

결론적으로, 다음은 동기비동기 빌드 종속성에 대한 단순한 gulp 패턴입니다.

//build sub-tasks
gulp.task('bar', ['clean'], function(){...});
gulp.task('foo', ['clean'], function(){...});
gulp.task('baz', ['clean'], function(){...});
...

//main build task
gulp.task('build', ['foo', 'baz', 'bar', ...], function(){...})

은 Gulp을 실행하기에 하다.clean 1회 1회 build의 수에 build는 「」에 clean 같 .같같 . .clean 모든 이 동기화 장벽이 됩니다.build되며, 그 후 의존관계는 병렬로 진행됩니다.buildsnowledge.

저에게는 연결된 입력을 예상하기 때문에 연결 후 미니파이 태스크를 실행하지 않았습니다.또한 몇 번 생성되지 않았습니다.

실행 순서대로 기본 태스크에 추가하려고 했지만 작동하지 않았습니다.1개만 더하면 된다.return각 태스크에 대해 최소화를 실현합니다.gulp.start()아래와 같이.

/**
* Concatenate JavaScripts
*/
gulp.task('concat-js', function(){
    return gulp.src([
        'js/jquery.js',
        'js/jquery-ui.js',
        'js/bootstrap.js',
        'js/jquery.onepage-scroll.js',
        'js/script.js'])
    .pipe(maps.init())
    .pipe(concat('ux.js'))
    .pipe(maps.write('./'))
    .pipe(gulp.dest('dist/js'));
});

/**
* Minify JavaScript
*/
gulp.task('minify-js', function(){
    return gulp.src('dist/js/ux.js')
    .pipe(uglify())
    .pipe(rename('ux.min.js'))
    .pipe(gulp.dest('dist/js'));
});

gulp.task('concat', ['concat-js'], function(){
   gulp.start('minify-js');
});

gulp.task('default',['concat']); 

출처: http://schickling.me/synchronous-tasks-gulp/

Gulp 및 Node는 약속을 사용합니다.

다음과 같이 할 수 있습니다.

// ... require gulp, del, etc

function cleanTask() {
  return del('./dist/');
}

function bundleVendorsTask() {
  return gulp.src([...])
    .pipe(...)
    .pipe(gulp.dest('...'));
}

function bundleAppTask() {
  return gulp.src([...])
    .pipe(...)
    .pipe(gulp.dest('...'));
}

function tarTask() {
  return gulp.src([...])
    .pipe(...)
    .pipe(gulp.dest('...'));
}

gulp.task('deploy', function deployTask() {
  // 1. Run the clean task
  cleanTask().then(function () {
    // 2. Clean is complete. Now run two tasks in parallel
    Promise.all([
      bundleVendorsTask(),
      bundleAppTask()
    ]).then(function () {
      // 3. Two tasks are complete, now run the final task.
      tarTask();
    });
  });
});

스트림을 gulp을 할 수 .then()메서드를 지정합니다.할 수도 .Promise을 사용법에서는 는는 here here here here here here here here here here를 씁니다.Promise.all()모든 약속이 해결되었을 때 호출되는 콜백을 1개 가질 수 있습니다.

작업이 완료되었는지, 그리고 나머지 작업이 완료되었는지 확인하는 방법은 다음과 같습니다.

gulp.task('default',
  gulp.series('set_env', gulp.parallel('build_scss', 'minify_js', 'minify_ts', 'minify_html', 'browser_sync_func', 'watch'),
    function () {
    }));

칭찬: https://fettblog.eu/gulp-4-parallel-and-series/

로 수행하기 인 솔루션(두과 같습니다 (미국의)
gulp.task('watch', () =>
gulp.watch(['src/**/*.css', 'src/**/*.pcss'], gulp.series('build',['copy'])) );
은, 「」를 할 가 있는 경우를 합니다.first-task 전에second-task 과제작성할 수 없다)를 합니다.copy이 경우)는 대괄호로 묶습니다.
★★★
작업을 동시에 수행할 때까지 외부에는 둥근 괄호가 있어야 합니다.

이 해킹을 시도합니다:-) 비동기 버그용 Gulp v3.x Hack

Readme에서 모든 "공식적인" 방법을 시도했지만 효과가 없었지만, 이 방법은 효과가 있었습니다.gulp 4.x로 업그레이드 할 수도 있지만, 너무 많은 것을 망가뜨리기 때문에 업그레이드하지 않는 것이 좋습니다.실제 js 약속을 사용할 수도 있지만, 이것은 빠르고, 더럽고, 단순합니다:-) 기본적으로 다음을 사용합니다.

var wait = 0; // flag to signal thread that task is done
if(wait == 0) setTimeout(... // sleep and let nodejs schedule other threads

게시물을 확인하세요!

언급URL : https://stackoverflow.com/questions/22824546/how-to-run-gulp-tasks-sequentially-one-after-the-other

반응형