1

我在指向代理 URL 时无法理解 Browsersync serveStatic。从我的阅读看来,我应该能够将 CSS 注入代理网站。在实践中,虽然我似乎无法让它发挥作用。我已经使用 rewriteRules 将代理 URL 上的现有 CSS 文件替换为我的本地 CSS,但如果它不替换文件,我似乎不能只注入纯 CSS。要指定,我的 CSS 根本没有被加载。如果我查看网络流量,我看不到我的样式表正在加载。我误解了 serveStatic 还是我的配置不正确?下面是我的 Gulp 文件的简化摘录。

作为参考,我使用的是 Browsersync V2.8.3。

gulp.task('build-css', () => {
    return gulp.src('src/scss/**/*.scss')
        .pipe(gulpif(arg.sourcemap, sourcemaps.init()))
        .pipe(sassLint())
        .pipe(concat('styles.scss'))
        .pipe(sassLint.format())
        .pipe(sassLint.failOnError())
        .pipe(sass())
        .pipe(autoprefixer('last 10 versions'))
        .pipe(cssnano())
        .pipe(sourcemaps.write())
        .pipe(gulp.dest('web/css'))
        .pipe(browserSync.stream({ match: '**/*.css' }));
});

gulp.task('serve', () => {
    browserSync.init({
        proxy: 'www.sampleurl.com',
        serveStatic: ['web/css'],
        reloadDelay: 50,
        reloadDebounce: 250
    });
    gulp.watch('src/scss/**/*.scss', ['build-css']);
});
4

1 回答 1

4

由于某种原因,我完全错过了Browsersync 食谱部分。在那里我找到了我的解决方案。在那里我找到了一个名为Proxy example + injectioning custom css file的特定配方。从本质上讲,似乎没有办法只包含文件列表并在页面加载时将它们弹出。相反,它需要使用 snippetOptions 并匹配诸如 head 标签之类的东西。然后,您可以简单地将链接标签附加到匹配的头部内容。下面的代码是从配方中复制的。

var browserSync = require('browser-sync').create();

browserSync.init({
    proxy: "example.com",
    serveStatic: ["app/static"],
    files: "app/static/_custom.css",
    snippetOptions: {
        rule: {
            match: /<\/head>/i,
            fn: function (snippet, match) {
                return '<link rel="stylesheet" type="text/css" href="/_custom.css"/>' + snippet + match;
            }
        }
    }
});
于 2017-11-17T15:16:25.103 回答