Gulp-inject不能和gulp-watch一起工作

gulp-inject not working with gulp-watch

本文关键字:一起 工作 gulp-watch 不能 Gulp-inject      更新时间:2023-09-26

我使用gulp-inject来自动添加SASS导入,因为它们是在我的项目中新创建的。这工作得很好,新的SASS文件被正确导入,但是当一个已经导入的文件被删除时,gulp-watch正在运行,它崩溃,并出现以下错误:

 Error: _dev'style'style.scss
Error: File to import not found or unreadable: components/_test - Copy.scss
       Parent style sheet: stdin
        on line 2 of stdin
>> @import "components/_test - Copy.scss";

我花了好几个小时试图弄清楚为什么它试图编译带有过时导入的旧版本的样式表。我在SASS任务上设置了一个延迟,当gulp-sass运行时,实际文件中的导入是正确的。我读到gulp-watch可能正在缓存样式表,但真的不确定。

下面是我的Gulp文件的相关部分,底部是我的完整Gulp文件的链接。

这是我的手表任务:(组件任务触发SASS任务)

// SASS
plugins.watch([paths.dev+'/**/*.scss',!paths.dev+'/style/components/**/*.scss'], function () {gulp.start(gulpsync.sync([
    'build-sass'
]));});
// COMPONENTS
plugins.watch(paths.dev+'/style/components/**/*.scss', function () {gulp.start(gulpsync.sync([
    'inject-deps'
]));});
<<p> SASS任务/strong>
gulp.task('build-sass', function() {
    // SASS
    return gulp.src(paths.dev+'/style/style.scss')
    .pipe(plugins.wait(1500))
    .pipe(plugins.sass({ noCache: true }))
    .pipe(gulp.dest(paths.tmp+'/style/'));
});
<<p> 注入任务/strong>
gulp.task('inject-deps', function() {
    // Auto inject SASS
    gulp.src(paths.dev+'/style/style.scss')
    .pipe(plugins.inject(gulp.src('components/**/*.scss', {read: false, cwd:paths.dev+'/style/'}), {
        relative: true,
        starttag: '/* inject:imports */',
        endtag: '/* endinject */',
        transform: function (filepath) {
            return '@import "' + filepath + '";';
        }
    }))

FULL GULP FILE:https://jsfiddle.net/cwu0m1cp/

正如所要求的,这里是带有导入的SASS文件,只要watch任务没有运行,它就可以正常工作,导入的文件不包含CSS:

SASS文件删除前:

/* inject:imports */
@import "components/_test.scss";
@import "components/_test-copy.scss";
/* endinject */

SASS文件删除后:

/* inject:imports */
@import "components/_test.scss";
/* endinject */

每当您删除style/components/中的文件时,您的build-sass任务就会启动。此时inject-deps任务还没有运行,相应的@import还没有被删除。

发生这种情况的原因是因为这一行:

plugins.watch([paths.dev+'/**/*.scss',!paths.dev+'/style/components/**/*.scss']

你实际上并没有在这里创建一个开头有!的字符串。您正在否定 paths.dev字符串,其计算结果为false (JavaScript万岁!)。所以你的路径是'false_dev/style/components/**/*.scss'

应该是这样:

plugins.watch([paths.dev+'/**/*.scss','!' + paths.dev+'/style/components/**/*.scss']
(别担心。我也花了很长时间才弄明白…)