简体   繁体   中英

Can I tell browser-sync to always use one .html file? (for html5mode links)

I use browser-sync ( https://github.com/shakyShane/browser-sync ) in my gulp file for development purposes. I want to use html5mode within my angular app. For that server needs to route multiple url patterns to single html file. Staging and production servers already do that but I would also like to have this up and running during development.

Here is how I run browser-sync server (part of gulpfile.js ):

gulp.task('serve', function () {
    browserSync.init(null, {
        server: {
            baseDir: [APP_PATH]
        }
    });

    // watch only for app specific codes;
    ...
});

Just to make it more clear, at my app js I instruct angular to use html5mode for routing:

$locationProvider.html5Mode(true);

Within my APP_PATH I have single index.html which is served when I access browser-sync server. What I need is that browser-sync serves this single file for each paths.

So for example if I try to reach /users/2 path starting from root path everything is fine; however if I refresh page or try to reach /users/2 directly, browser-sync tells that it cannot find proper document to serve - this is all good and understandable but I wonder if there is any way to tell browser-sync built-in server to serve one file only. If not, can anyone suggest other options? Should I simply run express server and tell browser-sync to proxy through it?

You can use https://github.com/tinganho/connect-modrewrite .

var modRewrite  = require('connect-modrewrite');

gulp.task('serve', function () {
    browserSync.init(null, {
        server: {
            baseDir: [APP_PATH],
            middleware: [
                modRewrite([
                    '!\\.\\w+$ /index.html [L]'
                ])
            ]
        }
    });

   // watch only for app specific codes;
   ...
});

From https://github.com/BrowserSync/browser-sync/issues/204#issuecomment-102623643

First install connect-history-api-fallback :

npm --save-dev install connect-history-api-fallback

Then add it to your gulpfile.js:

var historyApiFallback = require('connect-history-api-fallback');

gulp.task('serve', function() {
  browserSync.init({
    server: {
      baseDir: "app",
      middleware: [ historyApiFallback() ]
    }
  });
});

In version 2.23.0 you can use single option, like this:

gulp.task('serve', function () {
    browserSync.init(null, {
        server: {
            baseDir: [APP_PATH]
        },
        single: true
    });

    // watch only for app specific codes;
    ...
});

Reference: https://browsersync.io/docs/options#option-single

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM