我想通过gulp sass提高我的工作效率,因此我想在我的sass文件中更改某些内容时使用autoreload简单地重新加载我的页面,问题是我没有找到合适的解决方案。有人知道这是如何工作的吗?
我写的gulpfile就在这里:
var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('sass', function() {
return gulp.src('./sass/*.scss')
.pipe(sass())
.pipe(gulp.dest('./css'));
});
gulp.task('watch', function() {
gulp.watch('./sass/*.scss', ['sass'])
});
gulp.task('default', ['sass', 'watch']);
答案 0 :(得分:1)
有许多方法可以获得自动重新加载功能,下面的示例使用gulp-connect。我还在此示例中保留了其他几个有用的SCSS编译流程,添加了注释以便您了解。
"use strict";
var autoprefixer = require("autoprefixer");
var gulp = require("gulp");
var connect = require("gulp-connect");
var plumber = require("gulp-plumber");
var postcss = require("gulp-postcss");
var sass = require("gulp-sass");
gulp.task('server', function () {
connect.server({ // Create local server that will auto-reload itself upon changes into project
root: '.', // Path to WEB root (NOT simply root!) of your project
livereload: true
});
});
gulp.task('css', function () {
return gulp.src('./sass/**/*.scss') // Notice changed glob, it will allow you to compile scss files that are resides into deeper directories
.pipe(plumber()) // Plumber is useful to avoid crashing Gulp in a case if plugin throws exception
.pipe(sass().on('error', sass.logError)) // Make sure that errors are logged
.pipe(postcss([ // PostCSS plugins run, Autoprefixer in particular
autoprefixer({browsers: ['last 2 versions', 'IE >= 11', '> 1%']})
]))
.pipe(gulp.dest('./css')) // Save resulted CSS
.pipe(connect.reload()); // Re-load browser so changes will became visible
}
);
gulp.task('default', ['css']); // Compile CSS by default
gulp.task('watch', ['server', 'default'], function () { // Make sure that server is launched in a case if we're running watching
gulp.watch([
'./sass/**/*.scss'
], ['css']);
});
设置本地服务器后,您可以通过localhost:8080
或gulp watch
gulp server
通过range(2,2)
与您的项目联系。
答案 1 :(得分:1)
我会使用browserSync
。它是具有实时重载功能的高度可配置的本地服务器。 It's a nice match for gulp
运行gulp default
后,您可以http://localhost:3000
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
// Init browserSync
gulp.task('browser-sync', function() {
browserSync.init({
server: {
baseDir: "./",
directory: true
}
});
});
gulp.task('sass', function() {
return gulp.src('./sass/*.scss')
.pipe(sass())
.pipe(gulp.dest('./css'))
// Stream changes to browserSync to live reload CSS changes
.pipe(browserSync.stream());
});
gulp.task('watch', function() {
gulp.watch('./sass/*.scss', ['sass'])
});
// Add browserSync-init to default task
gulp.task('default', ['sass', 'watch', 'browser-sync']);