【问题标题】:How to sync all html files using gulp browsersync?如何使用 gulp browsersync 同步所有 html 文件?
【发布时间】:2016-11-30 03:01:22
【问题描述】:

我有一个这样的目录结构...

--app
 -css
  custom.css
 -sass
  custom.scss
 -pages
  about.html
  home.html
--gulpfile.js
--node_modules
--package.json

我的 gulp 文件是

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

gulp.task('sass', function () {
    return gulp.src('app/sass/*.scss')
        .pipe(sass())
        .pipe(gulp.dest('app/css/'))
        .pipe(browserSync.reload({
            stream: true
        }))
});

gulp.task('watch', ['browserSync', 'sass'], function () {
    gulp.watch('app/sass/*.scss', ['sass']);
    gulp.watch('app/pages/*.html', browserSync.reload);
    gulp.watch('app/js/**/*.js', browserSync.reload);
})

gulp.task('browserSync', function () {
    browserSync.init({           
        server: {
            baseDir: "app",
            index: "pages/home.html"
        },
        })
})

当我运行 watch 任务时,我被重定向到 localhost:3000,这将打开我的 home.html 页面。我的浏览器同步工作正常。

但是当我右键单击 about.html 文件并在 Visual Studio 的浏览器中查看它时,浏览器同步在 about.html 页面中不起作用。此页面在浏览器中打开为 localhost:56060/app/pages/about.html。

如何使浏览器同步在 pages 目录内的所有 html 文件中工作?

或者浏览器访问about.html文件的url地址应该是什么?

【问题讨论】:

  • 您在这里使用了两个不同的端口。尝试将 browsersync 端口也设置为 56060。
  • 我尝试使用 gulp.task('browserSync', function () { browserSync.init({ port: 56060, server: { baseDir: "app", index: "pages/home.html" }, }) })... 但之后当我运行监视任务时,我被重定向到localhost:56061
  • 您是否尝试使用代理:'localhost:56060' 而不是端口?
  • 我也试过了。它还没有工作,它显示页面未找到。

标签: gruntjs gulp


【解决方案1】:

您的代码看起来不错,请在浏览器“chrome”中尝试通过 url 地址,当然在您的 CMD 控制台命令 gulp watch 被激活时

http://localhost:3000/pages/about.html

请记住,如果您在您的情况下激活了 browserSync,它会在文件夹 app 中启动,这是您的 localhost:3000 服务器,类似于 localhost:56060 它不是您的页面。

在您的 html 文件中,不要忘记在 css 链接中在 css 文件夹之前添加“/”。

 <link rel="stylesheet" href="/css/custom.css">

如果仍有问题,请在 gulp task watch 中尝试此代码:

gulp.task('watch', ['browserSync', 'sass'], function () {
    gulp.watch('app/sass/*.scss', ['sass']);
    // gulp.watch('app/pages/*.html', browserSync.reload); // Comment this line 
    gulp.watch("app/**/*.html").on('change', browserSync.reload); // Try this line
    gulp.watch('app/js/**/*.js', browserSync.reload);
})

gulp.task('browserSync', function () {
    browserSync.init({           
        server: {
            baseDir: "app",
            index: "pages/home.html"
        },
        })
})

问候:)

【讨论】:

  • 是的,这样我可以在浏览器中访问 about.html,但它没有连接到浏览器同步,即每当我进行更改时,它不会直接反映在 about 页面中。我每次都必须刷新该页面才能看到更改,而 browserSync 似乎对 home.html 工作正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多