const gulp = require('gulp')
const scss = require('gulp-sass')
const sourceMap = require('gulp-sourcemaps')
const browserSync = require('browser-sync')
const reload = browserSync.reload
let folder = 'src'
// 以下两行为代理ajax请求
const proxyMiddleware = require('http-proxy-middleware')
const proxy = proxyMiddleware('/services', {target: 'http://localhost:8080', changeOrigin: true})
gulp.task('scss', function () {
  let src = './' + folder + '/**/*.scss'
  return gulp.src(src)
    .pipe(sourceMap.init({loadMaps: true}))
    .pipe(scss())
    .pipe(sourceMap.write('.'))
    .pipe(gulp.dest('./' + folder))
})
gulp.task('server', function () {
  //配置browserSync
  browserSync.init({
    server: {
      baseDir: './src',   // http服务的目录，这是根目录
      middleware: [proxy],    // 使用中间件配置代理
      index: 'index.htm'
    },
    port: 3003   // 本地服务端口
  })
  gulp.watch(['./' + folder + '/**/*.scss'], ['scss'])
  gulp.watch(['./' + folder + '/**/*', '!./' + folder + '/**/*.scss']).on('change', reload)  // 监听src目录下的文件改变，然后重载
})
