我可以告诉浏览器同步总是使用一个.html文件吗?(对于html5mode链接)

luk*_*szb 14 javascript node.js angularjs

我在gulp文件中使用browser-sync(https://github.com/shakyShane/browser-sync)进行开发.我想在我的角应用程序中使用html5mode.对于该服务器,需要将多个url模式路由到单个html文件.暂存和生产服务器已经这样做但我也想在开发期间启动并运行它.

以下是我运行browser-sync服务器的方法(部分gulpfile.js):

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

    // watch only for app specific codes;
    ...
});
Run Code Online (Sandbox Code Playgroud)

为了更清楚,在我的app js我指示angular使用html5mode进行路由:

$locationProvider.html5Mode(true);
Run Code Online (Sandbox Code Playgroud)

在我的APP_PATH中,我有一个index.html在访问browser-sync服务器时提供的服务.我需要的是browser-sync为每个路径提供这个单个文件.

因此,例如,如果我尝试/users/2从根路径开始到达路径,一切都很好; 然而,如果我刷新页面或尝试/users/2直接到达,browser-sync告诉它找不到合适的文档 - 这一切都很好,可以理解,但我想知道是否有任何方法可以告诉browser-sync内置服务器只提供一个文件.如果没有,有人可以建议其他选择吗?我应该只运行快速服务器并browser-sync通过它告诉代理吗?

小智 28

您可以使用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;
   ...
});
Run Code Online (Sandbox Code Playgroud)


Osc*_*car 17

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

首先安装connect-history-api-fallback:

npm --save-dev install connect-history-api-fallback
Run Code Online (Sandbox Code Playgroud)

然后将其添加到您的gulpfile.js:

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

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