Gulp插件简介
一、gulp-file-include
gulp-file-include
是一个用于文件引入的gulp插件。
1、安装
npm install --save-dev gulp-file-include
2、语法
const fileinclude = require('gulp-file-include');
fileinclude的参数有两种类型:
fileinclude([prefix])
prefix为前缀,字符串类型,默认为@@
。
-
fileinclude([options])
options为配置项,object类型,其中的属性有:
-
prefix:前缀,字符串类型,默认为
@@
-
suffix:后缀,字符串类型,默认为
''
-
basepath
基路径,字符串类型,可能的值有:
-
@file
:文件所在的目录 -
@root
:gulp运行的目录 -
path/to/dir
:相对于设置的basepath值(自定义路径)
-
-
filters:内容的过滤器,object类型,默认为false
-
context:
if
、for
语句的上下文,object类型,可以定义if
、for
语句中用到的变量值 -
indent:是否缩进,boolean类型,默认为false
-
注:gulpfile.js
最好使用UTF-8
编码,否则会有中文乱码问题。
3、样例一
此样例演示options的配置:
- index.html
<!DOCTYPE html>
<html>
<body>
@@include('./title.html')
@@include('./introduction.html', {
"name": "albert",
"age": 28,
"address": {
"country": "China",
"city": "BeiJing"
}
})
</body>
</html>
- title.html
<h1>Self Introduction</h1>
- introduction.html
<label>@@name</label>
<label>@@age</label>
<strong>@@address.country</strong>
<strong>@@address.city</strong>
- gulpfile.js
const gulp = require('gulp');
const fileinclude = require('gulp-file-include');
gulp.task('default', function(cb){
gulp.src('html/index.html')
.pipe(fileinclude({
indent: true,
prefix: '@@',
basepath: '@file'
}))
.pipe(gulp.dest('./dist/'));
cb();
});
执行gulp
命令,会在dist
目录下生成index.html
文件,内容如下:
<!DOCTYPE html>
<html>
<body>
<h1>Self Introduction</h1>
<label>albert</label>
<label>28</label>
<strong>China</strong>
<strong>BeiJing</strong>
</body>
</html>
4、样例二
此样例演示过滤器的使用(样例需安装markdownnpm install --save-dev markdown
):
- index.html
<!DOCTYPE html>
<html>
<body>
@@include(markdown('title.md'))
@@include('./introduction.html', {
"name": "albert",
"age": 28
})
</body>
</html>
- title.md
Hello World!
===
- introduction.html
<label>@@name</label>
<label>@@age</label>
gulpfile.js
const gulp = require('gulp');
const markdown = require('markdown');
const fileinclude = require('gulp-file-include');
gulp.task('default', function(cb){
gulp.src('html/index.html')
.pipe(fileinclude({
indent: true,
filters: {
markdown: markdown.parse
}
}))
.pipe(gulp.dest('./dist/'));
cb();
});
执行gulp
命令,会在dist
目录下生成index.html
文件,内容如下:
<!DOCTYPE html>
<html>
<body>
<h1>Hello World!</h1>
<label>albert</label>
<label>28</label>
</body>
</html>
5、样例三
此样例演示配置项context的使用:
- index.html
<!DOCTYPE html>
<html>
<body>
@@if(type === 'list'){
@@loop('article.html', [
{ "title": "My post title", "text": "<p>first...</p>" },
{ "title": "Another post", "text": "<p>second...</p>" },
{ "title": "One more post", "text": "<p>third...</p>" }
])
}
<ul>
@@for(var i = 0; i < arr.length; i++){
<li>`+arr[i]+`</li>
}
</ul>
@@loop('article.html', 'data.json')
</body>
</html>
- article.html
<article>
<h1>@@title</h1>
@@text
</article>
- data.json
[
{ "title": "My post title", "text": "<p>first...</p>" },
{ "title": "Another post", "text": "<p>second...</p>" },
{ "title": "One more post", "text": "<p>third...</p>" }
]
- gulpfile.js
const gulp = require('gulp');
const fileinclude = require('gulp-file-include');
gulp.task('default', function(cb){
gulp.src('html/index.html')
.pipe(fileinclude({
indent: true,
context: {
type: 'list',
arr: ['page1', 'page2']
}
}))
.pipe(gulp.dest('./dist/'));
cb();
});
执行gulp
命令,会在dist
目录下生成index.html
文件,内容如下:
<!DOCTYPE html>
<html>
<body>
<article>
<h1>My post title</h1>
<p>first...</p>
</article><article>
<h1>Another post</h1>
<p>second...</p>
</article><article>
<h1>One more post</h1>
<p>third...</p>
</article>
<ul>
<li>page1</li>
<li>page2</li>
</ul>
<article>
<h1>My post title</h1>
<p>first...</p>
</article><article>
<h1>Another post</h1>
<p>second...</p>
</article><article>
<h1>One more post</h1>
<p>third...</p>
</article>
</body>
</html>
二、gulp-rename
gulp-rename
可以重命名文件。
1、安装
npm install --save-dev gulp-rename
2、样例
- 重命名为一个固定值
const gulp = require('gulp');
const rename = require('gulp-rename');
gulp.task('default', function(cb){
gulp.src('./hello.txt')
.pipe(rename('./goodbye.md'))
.pipe(gulp.dest('./dist'));
cb();
});
结果:
./dist/goodbye.md
- 通过修改函数参数重命名
const gulp = require('gulp');
const rename = require('gulp-rename');
gulp.task('default', function(cb){
gulp.src('./hello.txt')
.pipe(rename(function(path){
path.dirname += '/test';
path.basename += '-goodbye';
path.extname = '.md';
})).pipe(gulp.dest('./dist'));
cb();
});
结果:
./dist/test/hello-goodbye.md
- 通过在函数中返回新对象重命名
const gulp = require('gulp');
const rename = require('gulp-rename');
gulp.task('default', function(cb){
gulp.src('./hello.txt')
.pipe(rename(function(path){
return {
dirname: path.dirname + "/test",
basename: path.basename + "-goodbye",
extname: ".md"
};
})).pipe(gulp.dest('./dist'));
cb();
});
结果同上。
- 通过一个固定对象重命名
const gulp = require('gulp');
const rename = require('gulp-rename');
gulp.task('default', function(cb){
gulp.src('./hello.txt', {base: process.cwd()})
.pipe(rename({
dirname: "main/result/test",
basename: "hi",
prefix: "yesterday-",
suffix: "-tomorrow",
extname: ".md"
})).pipe(gulp.dest('./dist'));
cb();
});
结果:
./dist/main/result/test/yesterday-hi-tomorrow.md
三、gulp-uglify
gulp-uglify
可以用来压缩Javascript文件。
1、安装
npm install --save-dev gulp-uglify
2、样例
将src目录下的JS文件混淆压缩到dist目录下:
- gulpfile.js
var gulp = require('gulp');
var uglify = require('gulp-uglify');
gulp.task('default', function(cb){
gulp.src('src/*.js').pipe(uglify()).pipe(gulp.dest('./dist'));
cb();
});
执行gulp命令后会看到在dist目录下生成了对应的压缩后的文件。
也可以使用readable-stream
的pipeline()
替换pipe()
方法:
安装readable-stream
:
npm install --save-dev readable-stream
- gulpfile.js
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var pipeline = require('readable-stream').pipeline;
gulp.task('default', function(cb){
pipeline(gulp.src('src/*.js'), uglify(), gulp.dest('dist/'));
cb();
});
- 效果
压缩前的JS文件:
function Person(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
var jack = new Person('Jack', 18, 'male');
压缩后的JS文件:
function Person(e,n,a){this.name=e,this.age=n,this.gender=a}var jack=new Person("Jack",18,"male");
四、gulp-concat
gulp-concat
可以用来连接文件。
1、安装
npm install --save-dev gulp-concat
2、样例-合并文件
将src目录下的JS文件连接到dist目录下的一个文件all.js
中:
- gulpfile.js
var gulp = require('gulp');
var concat = require('gulp-concat');
gulp.task('default', function(cb){
gulp.src('src/*.js').pipe(concat('all.js')).pipe(gulp.dest('./dist'));
cb();
});
也可以在gulp.src()
中指定顺序,并用concat方法的第二个参数设置换行符:
var gulp = require('gulp');
var concat = require('gulp-concat');
gulp.task('default', function(cb){
gulp.src(['src/bar.js', 'src/foo.js']).pipe(concat('all.js', {newLine: '\r\n'})).pipe(gulp.dest('./dist'));
cb();
});
- 效果
bar.js
:
console.log('Hello World!');
foo.js
:
function Person(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
var jack = new Person('Jack', 18, 'male');
执行gulp合并后的内容all.js
:
console.log('Hello World!');
function Person(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
var jack = new Person('Jack', 18, 'male');
3、样例-Source maps
- 安装gulp-sourcemaps
npm install --save-dev gulp-sourcemaps
- gulpfile.js
var gulp = require('gulp');
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');
gulp.task('default', function(cb){
gulp.src('src/*.js')
.pipe(sourcemaps.init())
.pipe(concat('all.js'))
.pipe(sourcemaps.write())
.pipe(gulp.dest('dist'));
cb();
});
- 效果
src/foo.js
:
function Person(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
var jack = new Person('Jack', 18, 'male');
src/bar.js
:
console.log('Hello World!');
执行gulp合并后的all.js
:
console.log('Hello World!');
function Person(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
var jack = new Person('Jack', 18, 'male');
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImJhci5qcyIsImZvby5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtBQ0FBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImFsbC5qcyIsInNvdXJjZXNDb250ZW50IjpbImNvbnNvbGUubG9nKCdIZWxsbyBXb3JsZCEnKTsiLCJmdW5jdGlvbiBQZXJzb24obmFtZSwgYWdlLCBnZW5kZXIpIHtcclxuICAgIHRoaXMubmFtZSA9IG5hbWU7XHJcbiAgICB0aGlzLmFnZSA9IGFnZTtcclxuICAgIHRoaXMuZ2VuZGVyID0gZ2VuZGVyO1xyXG59XHJcblxyXG52YXIgamFjayA9IG5ldyBQZXJzb24oJ0phY2snLCAxOCwgJ21hbGUnKTsiXX0=
五、gulp-minify-css
gulp-minify-css
插件通过对clean-css
的包装来实现css文件的压缩。
1、安装
npm install --save-dev gulp-minify-css
2、样例
- gulpfile.js
var gulp = require('gulp');
var minifyCSS = require('gulp-minify-css');
gulp.task('default', function(cb){
gulp.src('css/*.css')
.pipe(minifyCSS())
.pipe(gulp.dest('dist'));
cb();
});
- 效果
原CSS文件:
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
执行gulp后的CSS文件:
body{line-height:1}ol,ul{list-style:none}
3、参数
- keepBreaks
是否换行,默认为false。
minifyCSS({keepBreaks: true})
设置为true的效果:
body{line-height:1}
ol,ul{list-style:none}
- compatibility
控制兼容模式的使用,默认值为ie10+
.
- advanced
使用选择器、属性合并等高级优化,默认为true。
p{
font-size: 14px;
}
p{
text-align: center;
}
执行gulp后的样式会合并(包括@import
的文件中的样式):
p{font-size:14px;text-align:center}
- processImport
是否处理@import
规则,默认为true。
4、Source maps
使用gulp-sourcemaps
生成Source maps:
gulpfile.js:
var gulp = require('gulp');
var minifyCSS = require('gulp-minify-css');
var sourcemaps = require('gulp-sourcemaps');
gulp.task('default', function(cb){
gulp.src('css/*.css')
.pipe(sourcemaps.init())
.pipe(minifyCSS())
.pipe(sourcemaps.write())
.pipe(gulp.dest('dist'));
cb();
});
原CSS:
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
处理后的CSS:
body{line-height:1}ol,ul{list-style:none}
/*# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImluZGV4LmNzcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxLQUNDLFlBQWEsRUFFZCxHQUFJLEdBQ0gsV0FBWSIsImZpbGUiOiJpbmRleC5jc3MiLCJzb3VyY2VzQ29udGVudCI6WyJib2R5IHtcclxuXHRsaW5lLWhlaWdodDogMTtcclxufVxyXG5vbCwgdWwge1xyXG5cdGxpc3Qtc3R5bGU6IG5vbmU7XHJcbn1cclxuIl19 */
五、综合样例
将所有的CSS文件和JS文件分别打包压缩:
- gulpfile.js
var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var minifyCSS = require('gulp-minify-css');
gulp.task('minifyCss', function(cb){
gulp.src('src/css/*.css')
.pipe(concat('all.css'))
.pipe(minifyCSS())
.pipe(gulp.dest('dist/css'));
cb();
});
gulp.task('minifyJs', function(cb){
gulp.src('src/js/*.js')
.pipe(concat('all.js', {newLine: '\r\n'}))
.pipe(gulp.dest('dist/js'))
.pipe(uglify())
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest('dist/js'));
cb();
});
gulp.task('build', gulp.parallel('minifyCss', 'minifyJs', function(cb){
console.log('done...');
cb();
}));
gulp.task('watch', function(cb){
gulp.watch(['src/js/*.js', 'src/css/*.css'], gulp.series('build', function(done){
done();
}));
});
gulp.task('default', gulp.series('build', 'watch', function(cb){
cb();
}));
- 说明
任务build为合并并压缩CSS文件和JS文件,在压缩JS文件时会同时生成合并未压缩的文件;
任务watch可以监视CSS文件和JS文件的变化,如果发生变化则执行build任务重新合并压缩;
默认执行gulp先合并压缩一次文件,之后监视到文件的变化时再合并压缩。