Nice programing

Gulp 파일이 변경 될 때마다 Gulp를 어떻게 다시 시작할 수 있습니까?

nicepro 2020. 11. 17. 21:04
반응형

Gulp 파일이 변경 될 때마다 Gulp를 어떻게 다시 시작할 수 있습니까?


나는 Gulpfile. 변경되는 즉시 다시 시작할 수 있습니까? CoffeeScript에서 개발 중입니다. 변경 사항이 저장되면 다시 시작하기 위해 Gulp수 있습니까 Gulpfile.coffee?


당신은 만들 수 있습니다 task그 의지 gulp.watch에 대한 gulpfile.js단순히 spawn다른 꿀꺽 꿀꺽의 child_process을 .

var gulp = require('gulp'),
    argv = require('yargs').argv, // for args parsing
    spawn = require('child_process').spawn;

gulp.task('log', function() {
  console.log('CSSs has been changed');
});

gulp.task('watching-task', function() {
  gulp.watch('*.css', ['log']);
});

gulp.task('auto-reload', function() {
  var p;

  gulp.watch('gulpfile.js', spawnChildren);
  spawnChildren();

  function spawnChildren(e) {
    // kill previous spawned process
    if(p) { p.kill(); }

    // `spawn` a child `gulp` process linked to the parent `stdio`
    p = spawn('gulp', [argv.task], {stdio: 'inherit'});
  }
});

yargs다시 시작해야 할 때 실행할 '주 작업'을 수락하기 위해 사용 했습니다. 따라서 이것을 실행하려면 다음을 호출합니다.

gulp auto-reload --task watching-task

테스트하려면 touch gulpfile.js또는 전화를 걸어 touch a.css로그를 확인하세요.


gulpfile 변경시 gulp를 다시 시작하기 위해 gulp.js cli 래퍼 인 gulper만들었습니다 .

꿀꺽 꿀꺽 꿀꺽 꿀꺽 꿀꺽 꿀꺽 마시기 만하면됩니다.

$ gulper <task-name>

이 목적을 위해 작은 쉘 스크립트를 사용합니다. 이것은 Windows에서도 작동합니다.

Ctrl+C스크립트를 중지하려면 누릅니다 .

// gulpfile.js
gulp.task('watch', function() {
    gulp.watch('gulpfile.js', process.exit);
});

Bash 쉘 스크립트 :

# watch.sh
while true; do
    gulp watch;
done;

Windows 버전 : watch.bat

@echo off
:label
cmd /c gulp watch
goto label

EADDRINUSECaio Cunha의 답변에서 솔루션에 많은 오류가 발생했습니다. 내 gulpfile은 connectLiveReload 로 로컬 웹 서버를 엽니 다 . 이전 프로세스가 종료되기 전에 새로운 gulp 프로세스가 이전 프로세스와 잠시 공존하는 것으로 보이므로 포트는 곧 죽을 프로세스에서 계속 사용됩니다.

여기에 공존 문제를 주위에 유도 할 수있는 유사한 솔루션입니다, (주로에 따라 ) :

var gulp = require('gulp');
var spawn = require('child_process').spawn;

gulp.task('gulp-reload', function() {
  spawn('gulp', ['watch'], {stdio: 'inherit'});
  process.exit();
});

gulp.task('watch', function() {
  gulp.watch('gulpfile.js', ['gulp-reload']);
});

꽤 잘 작동하지만 한 가지 심각한 부작용 이 있습니다. 마지막 꿀꺽 꿀꺽 프로세스가 터미널에서 분리됩니다. 따라서 gulp watch종료 할 때 고아 gulp 프로세스가 여전히 실행 중입니다. 나는 그 문제를 해결할 수 없었고, 여분의 gulp 프로세스를 수동으로 종료하거나 gulpfile.js에 구문 오류를 저장할 수 있습니다 .


이에 대한 또 다른 해결책은 require.cache.

var gulp = require('gulp');

var __filenameTasks = ['lint', 'css', 'jade'];
var watcher = gulp.watch(__filename).once('change', function(){
  watcher.end(); // we haven't re-required the file yet
                 // so is the old watcher
  delete require.cache[__filename];
  require(__filename);
  process.nextTick(function(){
    gulp.start(__filenameTasks);
  });
});

나는 이것이 매우 오래된 질문이라는 것을 알고 있지만 Google의 최고 댓글이므로 여전히 관련성이 높습니다.

소스 gulpfile.js가 사용중인 디렉토리와 다른 디렉토리에있는 경우 더 쉬운 방법 이 있습니다. (중요합니다!) gulp 모듈 gulp-newergulp-data를 사용 합니다.

var gulp          = require('gulp'         )
  , data          = require('gulp-data'    )
  , newer         = require('gulp-newer'   )
  , child_process = require('child_process')
;

gulp.task( 'gulpfile.js' , function() {
    return gulp.src( 'sources/gulpfile.js' ) // source
        .pipe( newer(     '.'            ) ) // check
        .pipe( gulp.dest( '.'            ) ) // write
        .pipe( data( function(file)        { // reboot
            console.log('gulpfile.js changed! Restarting gulp...') ;
            var t , args = process.argv ;
            while ( args.shift().substr(-4) !== 'gulp' ) { t=args; }
            child_process.spawn( 'gulp' , args , { stdio: 'inherit' } ) ;
            return process.exit() ;
        } ) )
    ;
} ) ;

다음과 같이 작동합니다.

  • 트릭 1 : gulp-newer 는 소스 파일이 현재 파일보다 최신 인 경우 다음 파이프 만 실행합니다. 이렇게하면 재부팅 루프가 없음을 확인할 수 있습니다.
  • 동안 루프 제거합니다 모든 것을하기 전에 우리가 인수를 통과 할 수 있도록 명령 문자열에서 꿀꺽 명령을 포함.
  • child_process.spawn 은 새로운 gulp 프로세스를 생성하고 입력 출력과 오류를 부모에게 파이프합니다.
  • 트릭 2 : process.exit 는 현재 프로세스를 종료합니다. 그러나 프로세스는 자식 프로세스가 완료 될 때까지 죽을 때까지 기다립니다.

파이프에 재시작 기능을 삽입하는 다른 방법이 많이 있습니다. 어쨌든 모든 gulpfile에서 gulp-data를 사용합니다. 자신의 솔루션에 대해 자유롭게 의견을 말하십시오. :)


다음은 일반적인 Gulp 작업 절차와 더 일치하는 @CaioToOn의 다시로드 코드의 또 다른 버전입니다. 또한에 의존하지 않습니다 yargs.

생성을 요구하고 프로세스 변수를 초기화합니다 ( yargs필요하지 않음).

var spawn = require('child_process').spawn;
var p;

기본 꿀꺽 꿀꺽 작업은 스포 너입니다.

gulp.task('default', function() {
  if(p) { p.kill(); }
  // Note: The 'watch' is the new name of your normally-default gulp task. Substitute if needed.
  p = spawn('gulp', ['watch'], {stdio: 'inherit'});
});

감시 작업은 아마도 기본 꿀꺽 꿀꺽 작업이었을 것입니다. 이름을 바꾸고 gulpfile을 감시하기 위해 watch추가하고 변경 사항에 gulp.watch()대해 default작업을 실행하십시오 .

gulp.task('watch', ['sass'], function () {
  gulp.watch("scss/*.scss", ['sass']);
  gulp.watch('gulpfile.js', ['default']);
});

이제 실행 gulp만하면 gulpfile을 변경하면 자동으로 다시로드됩니다!


이 코드를 시도하십시오 (win32 플랫폼 만)

gulp.task('default', ['less', 'scripts', 'watch'], function(){
    gulp.watch('./gulpfile.js').once('change' ,function(){
        var p;
        var childProcess = require('child_process');
        if(process.platform === 'win32'){
            if(p){
                childProcess.exec('taskkill /PID' + p.id + ' /T /F', function(){});
                p.kill();
            }else{
                p = childProcess.spawn(process.argv[0],[process.argv[1]],{stdio: 'inherit'});
            }
        }
    });
});

Visual Studio 작업 실행기와도 잘 작동하는 Windows 용 좋은 솔루션입니다.

/// <binding ProjectOpened='auto-watchdog' />
const spawn = require('child-proc').spawn,
      configPaths = ['Gulpconfig.js', 'bundleconfig.js'];

gulp.task('watchdog', function () {
    // TODO: add other watches here

    gulp.watch(configPaths, function () {
        process.exit(0);
    });
});

gulp.task('auto-watchdog', function () {
    let p = null;

    gulp.watch(configPaths, spawnChildren);
    spawnChildren();

    function spawnChildren() {
        const args = ['watchdog', '--color'];

        // kill previous spawned process
        if (p) {
            // You might want to trigger a build as well
            args.unshift('build');

            setTimeout(function () {
                p.kill();
            }, 1000);
        }

        // `spawn` a child `gulp` process linked to the parent `stdio`
        p = spawn('gulp', args, { stdio: 'inherit' });
    }
});

다른 답변과 비교하여 주요 변경 사항 :

  • Windows에서 child_process가 실패하므로 child-proc을 사용합니다.
  • The watchdog exits itself on changes of files because in Windows the gulp call is wrapped in a batch script. Killing the batch script wouldn't kill gulp itself causing multiple watches to be spawned over time.
  • Build on change: Usually a gulpfile change also warrants rebuilding the project.

Install nodemon globally: npm i -g nodemon

And add in your .bashrc (or .bash_profile or .profile) an alias:

alias gulp='nodemon --watch gulpfile.js --watch gulpfile.babel.js --quiet --exitcrash --exec gulp'

This will watch for file gulpfile.js and gulpfile.babel.js changes. (see Google)

P.S. This can be helpful for endless tasks (like watch) but not for single run tasks. I mean it uses watch so it will continue process even after gulp task is done. ;)


I've been dealing with the same problem and the solution in my case was actually very simple. Two things.

  1. npm install nodemon -g (or locally if you prefer)
  2. run with cmd or create a script in packages like this:

    "dev": "nodemon --watch gulpfile.js --exec gulp"
    
  3. The just type npm run dev

--watch specifies the file to keep an eye on. --exec says execute next in line and gulp is your default task. Just pass in argument if you want non default task.

Hope it helps.

EDIT : Making it fancy ;) Now while the first part should achieve what you were after, in my setup I've needed to add a bit more to make it really user friend. What I wanted was

  1. First open the page.
  2. Look for changes in gulpfile.js and restart gulp if there are any
  3. Gulp it up so keep an eye on files, rebuild and hot reload

If you only do what I've said in the first part, it will open the page every time. To fix it, create a gulp task that will open the page. Like this :

gulp.task('open', function(){
return gulp
.src(config.buildDest + '/index.html')
.pipe(plugins.open({
    uri: config.url
}));

Then in my main tasks I have :

gulp.task('default', ['dev-open']);
gulp.task('dev-open', function(done){
    plugins.sequence('build', 'connect', 'open', 'watch', done);
});
gulp.task('dev', function(done){
    plugins.sequence('build', 'connect', 'watch', done);
});

Then modifying your npm scripts to

"dev": "gulp open & nodemon --watch gulpfile.js --watch webpack.config.js --exec gulp dev"

Will give you exactly what you want. First open the page and then just keep live reloading. Btw for livereload I use the one that comes with connect which always uses the same port. Hope it works for you, enjoy!


Here's a short version that's easy to understand that you can set as a default task so you just need to type "gulp":

gulp.task('watch', function() {
  const restartingGulpProcessCmd = 'while true; do gulp watch2 --colors; done;';
  const restartingGulpProcess = require('child_process').exec(restartingGulpProcessCmd);
  restartingGulpProcess.stdout.pipe(process.stdout);
  restartingGulpProcess.stderr.pipe(process.stderr);
});

gulp.task('watch2', function() {
  gulp.watch(['config/**.js', 'webpack.config.js', './gulpfile.js'],
    () => {
      console.log('Config file changed. Quitting so gulp can be restarted.');
      process.exit();
    });

  // Add your other watch and build commands here
}

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

Install gulp-restart

npm install gulp-restart

This code will work for you.

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

gulp.task('watch', function() { gulp.watch(['gulpfile.js'], restart); })

it will restart gulp where you do changes on the gulpfile.js

참고URL : https://stackoverflow.com/questions/22886682/how-can-gulp-be-restarted-upon-each-gulpfile-change

반응형