//gulpfile.js文件:
const gulp = require('gulp');
const uglify = require('gulp-uglify'); //压缩js
const cleanCSS = require('gulp-clean-css'); //压缩css
const scss = require("gulp-scss"); //编译scss
const sass = require("gulp-sass"); //编译scss
const connect = require('gulp-connect'); //静态服务器
const Proxy = require('gulp-connect-proxy'); //静态服务器
const less = require('gulp-less'); //编译less
gulp.task('build', ['js', 'css', 'html', 'json', 'img', 'less','scss'], function () {
console.log("项目创建成功")
})
gulp.task('default', ['watch', 'serve']);
// //监听文件改变
gulp.task('watch', function () {
gulp.watch('js/*.js', ['js']);
gulp.watch('css/*.css', ['css']);
gulp.watch('*.html', ['html']);
gulp.watch(['json/*.json', '!package.json', '!package-lock.json'], ['json']);
gulp.watch('imgs/**', ['img']);
})
//压缩js
gulp.task('js', function () {
return gulp.src('js/*.js')
.pipe(uglify())
.pipe(gulp.dest('dist/js'))
.pipe(connect.reload());
});
//压缩js
gulp.task('css', function () {
return gulp.src('css/*.css')
.pipe(cleanCSS())
.pipe(gulp.dest('dist/css'))
.pipe(connect.reload());
});
//拷贝html文件
gulp.task('html', function () {
return gulp.src('*.html')
.pipe(gulp.dest('dist'))
.pipe(connect.reload());
});
//拷贝json文件
gulp.task('json', function () {
return gulp.src(['json/*.json', '!package.json', '!package-lock.json']) //排除'!package.json','!package-lock.json'文件
.pipe(gulp.dest('dist/json'))
.pipe(connect.reload());
});
//拷贝图片
gulp.task('img', function () {
return gulp.src(['imgs/**'])
.pipe(gulp.dest('dist/imgs'))
.pipe(connect.reload());
});
//编译less并压缩
gulp.task('less', function () {
return gulp.src(['less/*.less'])
.pipe(less())
.pipe(cleanCSS())
.pipe(gulp.dest('dist/css'))
.pipe(connect.reload());
});
//编译scss并压缩
gulp.task('scss',function () {
return gulp.src(['scss/*.scss'])
.pipe(sass())
.pipe(cleanCSS())
.pipe(gulp.dest('dist/css'))
.pipe(connect.reload());
});
//静态服务器
gulp.task('serve', function () {
connect.server({
root: 'dist',
port: 9000,
livereload: true, //热加载
})
})
index.html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="./css/index.css">
<script src="./js/jquery2.0.js"></script>
<script src="./js/index.js"></script>
</head>
<body>
<h1>我是首页</h1>
<div id="box"></div>
<script>
$('#box').load('./home.html')
</script>
</body>
</html>
服务器开启之后,谷歌浏览器控制台报跨域问题: