我可以告诉浏览器同步始终使用一个.html文件吗?(用于html5模式链接)

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

本文关键字:一个 文件 html 链接 模式 html5 用于 同步 浏览器 我可以      更新时间:2023-09-26

我使用浏览器同步(https://github.com/shakyShane/browser-sync)在我的gulp文件中,用于开发目的。我想在我的angular应用程序中使用html5mode。为此,服务器需要将多个url模式路由到单个html文件。暂存服务器和生产服务器已经做到了这一点,但我也希望在开发过程中启动并运行这一点。

以下是我如何运行browser-sync服务器(gulpfile.js的一部分(:

gulp.task('serve', function () {
    browserSync.init(null, {
        server: {
            baseDir: [APP_PATH]
        }
    });
    // watch only for app specific codes;
    ...
});

为了更清楚地说明,在我的应用js中,我指示angular使用html5mode进行路由:

$locationProvider.html5Mode(true);

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

例如,如果我试图从根路径开始到达/users/2路径,那么一切都很好;然而,如果我刷新页面或试图直接访问/users/2browser-sync告诉它找不到合适的文档来提供服务——这一切都很好,也可以理解,但我想知道是否有任何方法可以告诉browser-sync内置服务器只提供一个文件。如果没有,有人能提出其他选择吗?我应该简单地运行express服务器并告诉browser-sync通过它进行代理吗?

您可以使用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;
   ...
});

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

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

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

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

var historyApiFallback = require('connect-history-api-fallback');
gulp.task('serve', function() {
  browserSync.init({
    server: {
      baseDir: "app",
      middleware: [ historyApiFallback() ]
    }
  });
});

在2.23.0版本中,您可以使用single选项,如下所示:

gulp.task('serve', function () {
    browserSync.init(null, {
        server: {
            baseDir: [APP_PATH]
        },
        single: true
    });
    // watch only for app specific codes;
    ...
});

参考:https://browsersync.io/docs/options#option-单个