Gulp is very useful, after writing a good gulpfile.js file, the general situation in the command line gulp
can start the development environment, greatly simplifying the development process. However, there is a problem is not resolved, is to write the Gulpfile.js file process, if this time gulp
has been started, modify the Gulpfile.js file, the process does not change, we want to gulpfile.js file modification gulp
, Process can be restarted automatically
Let's take this scaffold gulp-simple as an example.
The original Gulpfile.js file is as follows:
const gulp = require('gulp')const browserSync = require('browser-sync').create()const reload = browserSync.reloadgulp.task('server', () => { browserSync.init({ server: { // 根目录,index.html 文件所在的目录 baseDir: './' } }) gulp.watch("*.html").on('change', reload);})gulp.task('default', ['server'])
Thinking, we actually need to listen to the Gulpfile.js file, then kill the original process and start a new process:
const gulp = require('gulp')const browserSync = require('browser-sync').create()const reload = browserSync.reloadconst spawn = require('child_process').spawngulp.task('gulp-autoreload', () => { // 保存进程,任何时候只能有一个 gulp 进程 var p // gulpfile.js 一旦改动,则重启进程 gulp.watch('gulpfile.js', spawnChildren) // 第一次启动任务的时候,会默认执行 server 任务开启本地服务 spawnChildren() function spawnChildren(e) { // 杀掉原来的进程 p && p.kill() // 开一个新的进程 // 原来的调用方式是 gulp server p = spawn('gulp', ['server'], {stdio: 'inherit'}) }})gulp.task('server', () => { browserSync.init({ server: { // 根目录,index.html 文件所在的目录 baseDir: './' } }) gulp.watch("*.html").on('change', reload)})gulp.task('default', ['gulp-autoreload'])
However, the same flaw, every time you modify the Gulpfile.js file, the browser opens a new tab, the same as the previous URL, if you modify the Gulpfile.js file more than once, it will open more than one tab, these tabs can work, there will be multiple TA b simultaneous refresh, cost performance
The above is explained from the principle, the actual development has simpler tools, recommended Gulper, after the global installation, using the same way as before gulp
, just changed a name
npm install -g gulper gulpgulper
Refer to how can Gulp is restarted upon each gulpfile change?
How do I automatically restart gulp after I modify the Gulpfile.js file?