无法读取 gulp 中未定义的 属性 'watch'

Cannot read property 'watch' of undefined in gulp

有人可以帮忙吗?我一直收到这个错误,我真的不知道还能做什么。当我在 cmd 中触发命令 gulp watch 时,我收到以下错误 TypeError: Cannot read property 'watch' of undefined

C:\Apache24\htdocs\Gulp>gulp watch
[10:37:07] Using gulpfile C:\Apache24\htdocs\Gulp\gulpfile.js
[10:37:07] Starting 'watch'...
[10:37:07] 'watch' errored after 4.16 ms
[10:37:07] TypeError: Cannot read property 'watch' of undefined
   at watch (C:\Apache24\htdocs\Gulp\gulpfile.js:42:10)
   at watch (C:\Apache24\htdocs\Gulp\node_modules\undertaker\lib\set-task.js:13:15)
   at bound (domain.js:422:14)
   at runBound (domain.js:435:12)
   at asyncRunner (C:\Apache24\htdocs\Gulp\node_modules\async-done\index.js:55:18)
   at processTicksAndRejections (internal/process/task_queues.js:75:11)
const {src, dest, series, gulp, parallel} = require('gulp');
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');

var styleSRC = './src/scss/style.scss';
var styleDIST = './dist/css/';


var jsSRC = './src/js/script.js';
var jsDIST = './dist/js/';


function style() {
    "use strict";
    return src(styleSRC)
        .pipe(sourcemaps.init())
        .pipe(sass({
            errorLogToConsole: true,
            outputStyle: 'compressed'
        }))
        .on('error', console.error.bind(console))
        .pipe(autoprefixer({
            overrideBrowserslist: ["defaults"],
            cascade: false
        }))
        .pipe(rename({basename: 'style', suffix: '.min'}))
        .pipe(sourcemaps.write('./'))
        .pipe(dest(styleDIST));
}


function js() {
    "use strict";
    return src(jsSRC)
        .pipe(dest(jsDIST));
}

const watch = function () {
    "use strict";
    gulp.watch('./src/scss/**/*.scss', {usePolling: true}, gulp.series(style));
    gulp.watch('./src/js/**/*.js', {usePolling: true}, gulp.series(js));
};
exports.default = series(
    parallel(style, js),
    watch
);

exports.watch = watch;
exports.js = js;
exports.style = style;

试试这个,删除 const 并将其定义为函数。

function watch() {
    "use strict";
    gulp.watch('./src/scss/**/*.scss', {usePolling: true}, gulp.series(style));
    gulp.watch('./src/js/**/*.js', {usePolling: true}, gulp.series(js));
};

我认为你的解构有点错误。你有:

const {src, dest, series, gulp, parallel} = require('gulp');
//                          ^ this does not exist - hence the undefined property

我想你想用watch替换解构中的gulp,所以现在是:

const {src, dest, series, watch, parallel} = require('gulp');

并在您的 watch 函数中执行:

// renamed the function to avoid conflict
const watchTask = function () {
    "use strict";
    watch('./src/scss/**/*.scss', {usePolling: true}, series(style));
    watch('./src/js/**/*.js', {usePolling: true}, series(js));
};

exports.default = series(
    parallel(style, js),
    watchTask
);

exports.watch = watchTask;