2

I'm having trouble understanding Browsersync serveStatic while pointed to a proxy URL. From my reading it seems that I should be able to inject CSS into the proxied website. In practice though I can't seem to get it to work. I have used rewriteRules to replace an existing CSS file on the proxy URL with my local CSS but I can't seem to just inject pure CSS if it's not replacing a file. To specify, my CSS is simply not being loaded. If I look at the network traffic, I don't see my stylesheet being loaded. Am I misunderstanding serveStatic or is my configuration incorrect? Below is a simplified extract from my Gulp file.

For reference I'm using 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']);
});
Sean
  • 313
  • 1
  • 17

1 Answers1

4

For some reason I completely missed the Browsersync recipes section. There I found my solution. There I found a specific recipe titled Proxy example + injecting custom css file. Essentially it looks like there is no way to just include a list of files and just pop them in on page load. Instead, it's required to use snippetOptions and match something like head tag. Then you can simply append a link tag to the matched head content. The code below is copied from the recipe.

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;
            }
        }
    }
});
Sean
  • 313
  • 1
  • 17
  • 1
    I am using to inject an entire React bundle. Is that what you mean by JavaScript? This matching functionality works for anything in the document so you can inject whatever you want into the match. https://github.com/srm985/axure-redline-tool/blob/feature/version-3-react-refactor/gulp.config.js#L18 – Sean Jan 16 '19 at 20:50
  • i see js added, but console.log('foo') didnt show up, gonna tinker with it, thanks. – DGRFDSGN Jan 17 '19 at 08:26