Gulp无法在文件变更时执行Browser-sync,报ERR_ASSERTION错误求助
问题描述
时隔数年重新使用Gulp,发现其变化较大。尝试通过Gulp和Browser-sync实现编辑HTML文件时自动刷新页面,但Gulp任务执行失败,报错如下:
AssertionError [ERR_ASSERTION]: Task function must be specified at Gulp.set [as _setTask] (/Users/me/dev/myProject/node_modules/undertaker/lib/set-task.js:10:3) at Gulp.task (/Users/me/dev/myProject/node_modules/undertaker/lib/task.js:13:8) at Object.<anonymous> (/Users/me/dev/myProject/gulpfile.js:11:6) at Module._compile (node:internal/modules/cjs/loader:1159:14) at Module._extensions..js (node:internal/modules/cjs/loader:1213:10) at Module.load (node:internal/modules/cjs/loader:1037:32) at Module._load (node:internal/modules/cjs/loader:878:12) at Module.require (node:internal/modules/cjs/loader:1061:19) at require (node:internal/modules/cjs/helpers:103:18) at requireOrImport (/usr/local/lib/node_modules/gulp-cli/lib/shared/require-or-import.js:19:11) { generatedMessage: false, code: 'ERR_ASSERTION', actual: false, expected: true, operator: '==' }
执行gulp --version命令后,显示版本信息:
CLI version: 2.3.0 Local version: 4.0.2
当前gulpfile.js内容:
var gulp = require('gulp'); var browserSync = require('browser-sync').create(); // Reloading browsers gulp.task('html-watch', function (done) { browserSync.reload(); done(); }); // Use default task to launch Browsersync and watch html files gulp.task('default', ['html-watch'], function () { // Serve files from the root of this project browserSync.init({ server: { baseDir: "./site" } }); // add browserSync.reload to the tasks array to make // all browsers reload after tasks are complete. gulp.watch("site/*.html", ['html-watch']); });
解决方案
报错核心原因是Gulp 4.x 废弃了Gulp 3.x中数组形式的任务依赖写法,同时gulp.watch的回调参数也不再支持数组形式的任务名。需要按照Gulp 4的语法修改gulpfile.js:
修改后的gulpfile.js
const gulp = require('gulp'); const browserSync = require('browser-sync').create(); // 定义刷新任务 function htmlWatch(done) { browserSync.reload(); done(); } // 定义启动服务并监听的任务 function serve() { // 启动本地服务 browserSync.init({ server: { baseDir: "./site" } }); // 监听HTML文件变化,触发刷新任务 gulp.watch("site/*.html", htmlWatch); } // 导出默认任务 exports.default = serve;
关键修改点说明
- 函数式任务定义:Gulp 4推荐直接将任务定义为函数,替代旧版
gulp.task('name', fn)的写法,更简洁直观 - 任务依赖替换:Gulp 3的数组形式依赖(如
['html-watch'])被移除,改用series(串行执行)或parallel(并行执行)方法组合任务,本案例中无需前置依赖,直接合并逻辑即可 - 监听回调调整:
gulp.watch的第二个参数直接传入任务函数,无需再用数组包裹
内容的提问来源于stack exchange,提问作者mbilyanov
相关产品推荐
相关产品推荐

