首页 > 解决方案 > Gulp:paths.scss.forEach 不是函数

问题描述

我写了以下 gulp 任务:

var paths = require('./package.json').paths;

var watching = false;

gulp.task('scss', function () {
    var processors = [
        autoprefixer({
            browsers: ['last 2 versions', '> 0.5%', 'ie >= 8', 'ie_mob >= 10', 'ff >= 30', 'chrome >= 34', 'ios >= 7', 'android >= 4']
        }),
        cssnano({
            autoprefixer: false,
            safe: true
        })
    ];
    var streams = merge();
    var development = (gutil.env.type === 'dev10');
    paths.scss.forEach(function (path) {
        streams.add(gulp.src(path.scss.src + '**/*.scss')
            .pipe(sourcemaps.init())
            .pipe(sass())
            .pipe(postcss(processors))
            .pipe(sourcemaps.write('./'))
            .pipe(gulp.dest(path.dest)));
    });
    return streams;
});
const watch = gulp.parallel('js', 'scss');

exports.watch = watch;

另一个任务在哪里js运行,没有任何错误。目前我一直在努力完成这项scss任务,因为我经常收到一条错误消息paths.scss.forEach is not a function。我在我的文件中写了以下内容,该文件与我的package.json文件位于同一目录中gulpfile.js

"paths": {
    "js": {
      "src": "../client/js/",
      "dest": "../static/default/js/"
    },
    "scss": {
      "src": "../client/scss/",
      "dest": "../static/default/css/"
    }
}

traceback在 CMD 中有以下内容:

[16:38:08] Starting 'watch'...
[16:38:08] Starting 'js'...
[16:38:08] Starting 'scss'...
[16:38:08] 'scss' errored after 84 ms
[16:38:08] TypeError: paths.scss.forEach is not a function
    at D:\XYZ\gulpfile.js:92:13
    at taskWrapper (D:\XYZ\node_modules\undertaker\lib\set-task.js:13:15)
    at bound (domain.js:280:14)
    at runBound (domain.js:293:12)
    at asyncRunner (D:\XYZ\node_modules\async-done\index.js:55:18)
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)
[16:38:08] 'watch' errored after 91 ms
[16:38:08] The following tasks did not complete: js
[16:38:08] Did you forget to signal async completion?

在这种情况下我应该怎么做,因为我现在被困住了,对如何进行没有任何想法。

标签: foreachgulpgulp-watchwatchify

解决方案


paths.scss是一个对象。 forEach是数组的属性。因此,请改用for in循环。

gulp.task('scss', function () {

  // paths.scss.forEach(function (path) {

  for (var path in paths.scss) {

    console.log(path);  // src, dest

      streams.add(gulp.src(path + '**/*.scss')

      // streams.add(gulp.src(path.scss.src + '**/*.scss')
      //     .pipe(sourcemaps.init())
      //     .pipe(sass())
      //     .pipe(postcss(processors))
      //     .pipe(sourcemaps.write('./'))
      //     .pipe(gulp.dest(path.dest)));
  };
  // return streams;
});

但无论如何你只想要path.scss.src- 你不想运行你的sass循环paths.scss.dest- 这就是你想要做的。完全摆脱 for 循环:

gulp.src(paths.scss.src + '**/*.scss')
  .pipe(sourcemaps.init())
  .pipe(sass())
  .pipe(postcss(processors))
  .pipe(sourcemaps.write('./'))
  .pipe(gulp.dest(paths.scss.dest)));

推荐阅读