用browser-sync进行实时刷新

1.添加gulp、gulp-sass、browser-sync组件

npm install --save-dev gulp gulp-sass browser-sync

会在package.json中添加如下内容:

  "devDependencies": {
    "browser-sync": "^2.10.1",
    "gulp": "^3.9.0",
    "gulp-sass": "^2.1.1"
  }

2.新建gulpfile.js文件

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

// Static Server + watching scss/html files
gulp.task('serve', ['sass'], function() {

    browserSync.init({
        server: "./src"
    });

    gulp.watch("src/scss/*.scss", ['sass']);
    // gulp.watch("src/*.html" ,browserSync.reload);
    gulp.watch("src/*.html").on('change', browserSync.reload);
});

// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
    return gulp.src("src/scss/*.scss")
        .pipe(sass())
        .pipe(gulp.dest("src/css"))
        .pipe(browserSync.stream());
});

gulp.task('default', ['serve']);

3.命令行运行gulp

gulp

4.浏览器打开页面

http://localhost:3000/
它会自动增加如下代码到html

<script async="" src="/browser-sync/browser-sync-client.2.10.1.js"></script>

5.参考地址

browsersync doc

猜你喜欢

转载自blog.csdn.net/attwice/article/details/50385364