前端构建工具Gulp打包入门介绍

发布于2017年9月09日 14:38:18

从上次的webpack打包不兼容低版本ie时,我放弃了webpack而选择了用gulp打包,下面来详细总结下打包流程。

1、按照老步骤借助npm安装好gulp,在根目录下新建src文件夹,再创建子目录文件夹,最终目录结构如下:

2、新建package.json文件,基本配置如下:

"devDependencies": {
"browser-sync": "^2.18.13",
"del": "^3.0.0",
"gulp": "^3.9.1",
"gulp-autoprefixer": "^4.0.0",
"gulp-clean": "^0.3.2",
"gulp-clean-css": "^3.8.0",
"gulp-concat": "^2.6.1",
"gulp-file-include": "^1.2.0",
"gulp-htmlmin": "^3.0.0",
"gulp-imagemin": "^3.3.0",
"gulp-less": "^3.3.2",
"gulp-rev": "^8.0.0",
"gulp-rev-append": "^0.1.8",
"gulp-rev-collector": "^1.2.2",
"gulp-sync": "^0.1.4",
"gulp-uglify": "^3.0.0"
}

3、新建gulpfile.js文件,我们需要新建gulpfile文件以指定gulp需要为我们完成什么任务。gulp只有五个方法: taskrunwatchsrc,和dest,在项目根目录新建一个js文件并命名为gulpfile.js。 基本配置如下所示:

//组建配置 ,具体可以访问官方文档或在一点查看

var gulp = require("gulp");
var del = require('del');
var less = require("gulp-less");
var browsersync = require('browser-sync').create();
var concat = require('gulp-concat');
var cssmin = require('gulp-clean-css');
var rev = require('gulp-rev');
var revCollector = require('gulp-rev-collector');
var rev = require('gulp-rev-append');
var imagemin = require('gulp-imagemin');
var fileinclude = require('gulp-file-include');
varuglify=require('gulp-uglify');
var autoprefixer = require('gulp-autoprefixer');
//删除dist目录下文件
gulp.task('clean', function (cb) {
returndel(['dist/*'],cb);
})
// 压缩less文件
gulp.task("less", function () {
gulp.src('src/assets/less/*.less')
.pipe(less())
.pipe(concat('style.css'))//合并后的文件名
.pipe(gulp.dest('dist/css'))
.pipe(browsersync.stream());
// .pipe(gulp.dest("src/assets/css"));
});
gulp.task('css', function () {
gulp.src('src/assets/css/*.css')
.pipe(cssmin({
advanced: false,//类型:Boolean 默认:true [是否开启高级优化(合并选择器等)]
compatibility: 'ie7',//保留ie7及以下兼容写法 类型:String 默认:''or'*' [启用兼容模式; 'ie7':IE7兼容模式,'ie8':IE8兼容模式,'*':IE9+兼容模式]
keepBreaks: true,//类型:Boolean 默认:false [是否保留换行]
keepSpecialComments: '*'
//保留所有特殊前缀 当你用autoprefixer生成的浏览器前缀,如果不加这个参数,有可能将会删除你的部分前缀
}))
.pipe(autoprefixer({
browsers: ['last 2 versions', 'Android >= 4.0'],
cascade: true, //是否美化属性值 默认:true 像这样:
//-webkit-transform: rotate(45deg);
// transform: rotate(45deg);
remove: true //是否去掉不必要的前缀 默认:true
}))
.pipe(gulp.dest('dist/css'))
});
// 压缩合并js文件
gulp.task('scripts', function () {
gulp.src('src/assets/js/*.js')
//.pipe(concat('all.js'))//合并后的文件名
//.pipe(uglify())
.pipe(gulp.dest('dist/js'))
.pipe(browsersync.stream());//文件有更新自动执行
});
// 压缩img
gulp.task('image', function () {
gulp.src('src/assets/images/*.{png,jpg,jpeg,gif}')
.pipe(imagemin())
.pipe(gulp.dest('dist/images'))
.pipe(browsersync.stream());
});
// gulp.task('rev', function () {
// gulp.src(['src/assets/rev/*.json', 'src/views/*.html']) //- 读取 rev-manifest.json 文件以及需要进行css名替换的文件
// .pipe(revCollector()) //- 执行文件内css名的替换
// .pipe(gulp.dest('dist')); //- 替换后的文件输出的目录
// });
// var htmlmin = require('gulp-htmlmin'); //html压缩插件
gulp.task('html', function () {
gulp.src(['src/views/*.html','!src/views/common/*.*'])
.pipe(fileinclude({
prefix: '@@',
basepath: '@file'
}))
// .pipe(htmlmin({
// collapseWhitespace: false, //压缩html
// collapseBooleanAttributes: false, //省略布尔属性的值
// removeComments: false, //清除html注释
// removeEmptyAttributes: false, //删除所有空格作为属性值
// removeScriptTypeAttributes: false, //删除type=text/javascript
// removeStyleLinkTypeAttributes: false, //删除type=text/style
// minifyJS:false, //压缩页面js
// minifyCSS:false //压缩页面css
// }))
.pipe(gulp.dest('dist'))
.pipe(browsersync.stream());
});
// 给静态文件添加hash值
// gulp.task('rev', function () {
// gulp.src('src/views/index.html')
// .pipe(rev())
// .pipe(gulp.dest('dist'));
// });
gulp.task('serve', ['clean'], function () {
gulp.start('less','css','scripts','image','html');
browsersync.init({
port: 3000,
server: {
baseDir: './dist'
}
});
//监控文件变化,自动更新
gulp.watch('src/assets/js/*.js',['scripts']);
gulp.watch(['src/assets/less/*.less'],['less']);
gulp.watch(['src/assets/css/*.css'],['css']);
gulp.watch('src/assets/images/*.*',['image']);
gulp.watch(['src/views/*.html'],['html']);
});
gulp.task('default', ['serve']);
这一步,我们引入了核心的gulp和其他依赖组件。

 

4、新建html静态文件,写点展示代码,把公共部分分离出来成模块,

公共模块均可以这种形式引入:@@include("src/views/common/header.html")

5、准备工作完成后,我们打开命令行工具,进入根目录文件夹,执行gulp命令:
如上图所示,基本的打包都已完成,这时根目录文件夹会多出一个我们放静态文件夹dist,里面放的都是我们打包后的内容。访问localhost:30000,如下图显示正常:
目前摸索的还很基础,后面有新的体会会继续补充,欢迎各位大神前来拍砖矫正。

本文共 28 个回复

  • mind vault 2025/10/14 23:54

    **mind vault** mind vault is a premium cognitive support formula created for adults 45+. It’s thoughtfully designed to help maintain clear thinking

  • sugarmute 2025/10/19 01:31

    **sugarmute** sugarmute is a science-guided nutritional supplement created to help maintain balanced blood sugar while supporting steady energy and mental clarity.

  • glpro 2025/10/19 05:48

    **glpro** glpro is a natural dietary supplement designed to promote balanced blood sugar levels and curb sugar cravings.

  • prostadine 2025/10/19 09:32

    **prostadine** prostadine is a next-generation prostate support formula designed to help maintain, restore, and enhance optimal male prostate performance.

  • vitta burn 2025/10/19 15:08

    **vitta burn** vitta burn is a liquid dietary supplement formulated to support healthy weight reduction by increasing metabolic rate, reducing hunger, and promoting fat loss.

  • glucore 2025/10/19 15:14

    **glucore** glucore is a nutritional supplement that is given to patients daily to assist in maintaining healthy blood sugar and metabolic rates.

  • prodentim 2025/10/19 15:15

    **prodentim** prodentim an advanced probiotic formulation designed to support exceptional oral hygiene while fortifying teeth and gums.

  • synaptigen 2025/10/19 15:34

    **synaptigen** synaptigen is a next-generation brain support supplement that blends natural nootropics, adaptogens

  • nitric boost 2025/10/19 15:35

    **nitric boost** nitric boost is a dietary formula crafted to enhance vitality and promote overall well-being.

  • mitolyn 2025/10/19 18:03

    **mitolyn** mitolyn a nature-inspired supplement crafted to elevate metabolic activity and support sustainable weight management.

  • wildgut 2025/10/19 18:10

    **wildgut** wildgutis a precision-crafted nutritional blend designed to nurture your dog’s digestive tract.

  • zencortex 2025/10/19 18:22

    **zencortex** zencortex contains only the natural ingredients that are effective in supporting incredible hearing naturally.

  • yu sleep 2025/10/19 19:13

    **yu sleep** yusleep is a gentle, nano-enhanced nightly blend designed to help you drift off quickly, stay asleep longer, and wake feeling clear.

  • breathe 2025/10/20 02:39

    **breathe** breathe is a plant-powered tincture crafted to promote lung performance and enhance your breathing quality.

  • pineal xt 2025/10/20 15:20

    **pineal xt** pinealxt is a revolutionary supplement that promotes proper pineal gland function and energy levels to support healthy body function.

  • energeia 2025/10/20 15:46

    **energeia** energeia is the first and only recipe that targets the root cause of stubborn belly fat and Deadly visceral fat.

  • prostabliss 2025/10/20 16:38

    **prostabliss** prostabliss is a carefully developed dietary formula aimed at nurturing prostate vitality and improving urinary comfort.

  • boostaro 2025/10/20 17:06

    **boostaro** boostaro is a specially crafted dietary supplement for men who want to elevate their overall health and vitality.

  • potentstream 2025/10/20 21:46

    **potentstream** potentstream is engineered to promote prostate well-being by counteracting the residue that can build up from hard-water minerals within the urinary tract.

  • hepatoburn 2025/10/21 13:16

    **hepatoburn** hepatoburn is a premium nutritional formula designed to enhance liver function, boost metabolism, and support natural fat breakdown.

  • hepato burn 2025/10/21 17:49

    **hepato burn** hepato burn is a potent, plant-based formula created to promote optimal liver performance and naturally stimulate fat-burning mechanisms.

  • flowforce max 2025/10/22 02:59

    **flowforce max** flowforce max delivers a forward-thinking, plant-focused way to support prostate health—while also helping maintain everyday energy, libido, and overall vitality.

  • prodentim 2025/10/22 04:19

    **prodentim** prodentim is a forward-thinking oral wellness blend crafted to nurture and maintain a balanced mouth microbiome.

  • cellufend 2025/10/22 04:49

    **cellufend** cellufend is a natural supplement developed to support balanced blood sugar levels through a blend of botanical extracts and essential nutrients.

  • revitag 2025/10/22 06:00

    **revitag** revitag is a daily skin-support formula created to promote a healthy complexion and visibly diminish the appearance of skin tags.

  • neuro genica 2025/10/22 06:04

    **neuro genica** neuro genica is a dietary supplement formulated to support nerve health and ease discomfort associated with neuropathy.

  • sleeplean 2025/10/23 06:11

    **sleeplean** sleeplean is a US-trusted, naturally focused nighttime support formula that helps your body burn fat while you rest.

  • memory lift 2025/10/25 00:37

    **memory lift** memory lift is an innovative dietary formula designed to naturally nurture brain wellness and sharpen cognitive performance.