首页 > Web开发 > 详细

gulpfile.js 文件配置

时间:2019-05-21 11:29:20      阅读:94      评论:0      收藏:0      [点我收藏+]
  1     // --本地服务器
  2     var gulp = require(‘gulp‘),
  3         browserSync = require(‘browser-sync‘).create(),
  4         // SSI = require(‘browsersync-ssi‘),
  5         reload = browserSync.reload,
  6         watch = require(‘gulp-watch‘),
  7         uglify = require(‘gulp-uglify‘),
  8         concat = require(‘gulp-concat‘),
  9         jshint = require(‘gulp-jshint‘),
 10         csscomb = require(‘gulp-csscomb‘),
 11         csslint = require(‘gulp-csslint‘),
 12         csso = require(‘gulp-csso‘),
 13         prefixer = require(‘gulp-autoprefixer‘),
 14         clean = require(‘gulp-clean‘),
 15         rename = require("gulp-rename"),
 16         zip = require(‘gulp-zip‘),
 17         imagemin = require(‘gulp-imagemin‘),
 18         pngquant = require(‘imagemin-pngquant‘),
 19         template = require(‘gulp-template‘),
 20         processhtml = require(‘gulp-processhtml‘),
 21         gulpif = require(‘gulp-if‘),
 22         minimist = require(‘minimist‘),
 23         fileinclude = require(‘gulp-file-include‘),
 24         shell = require(‘gulp-shell‘),
 25         less = require(‘gulp-less‘),
 26         config = require(‘./config.json‘),
 27         //确保本地已安装gulp-sourcemaps [cnpm install gulp-sourcemaps --save-dev]
 28         sourcemaps = require(‘gulp-sourcemaps‘),
 29         combiner = require(‘stream-combiner2‘),
 30         //确保本地已安装gulp-minify-css [cnpm install gulp-minify-css --save-dev]
 31         cssmin = require(‘gulp-minify-css‘);
 32         //确保本地已安装gulp-less [cnpm install gulp-less --save-dev]
 33 
 34     var knownOptions = {
 35         string: ‘env‘,
 36         default: {
 37             env: process.env.NODE_ENV || ‘dev‘
 38         }
 39     };
 40 
 41     var filetask = {
 42         string: ‘file‘,
 43         default: {
 44             file: process.env.NODE_ENV || ‘all‘
 45         }
 46     };
 47 
 48     // --env dev
 49     // --env pro
 50 
 51     var options = minimist(process.argv.slice(2), knownOptions, filetask);
 52 
 53 
 54     // ----- js -----
 55     gulp.task(‘jstask‘, function() {
 56         if (!options.file) {
 57             console.log(‘检查全部js文件‘);
 58             console.log(‘运行gulp jstask --file 文件名,查看对应文件错误信息‘);
 59             return gulp.src(‘./images/*.js‘)
 60                 // .pipe(watch(‘./src/images/*.js‘)) // 只重新编译被更改过的文件
 61                 // js检查
 62                 .pipe(jshint())
 63                 .pipe(jshint.reporter(‘fail‘));
 64         } else {
 65             console.log(‘检查js文件: ./images/‘ + options.file);
 66             return gulp.src(‘./images/‘ + options.file)
 67                 // .pipe(watch(‘./src/images/*.js‘)) // 只重新编译被更改过的文件
 68                 // js检查
 69                 .pipe(jshint())
 70                 .pipe(jshint.reporter(‘default‘));
 71         }
 72 
 73     });
 74 
 75 
 76 
 77     // js压缩发布
 78     gulp.task(‘jstask-min‘, [‘jstask‘], function() {
 79         return gulp.src(‘./build/*.js‘)
 80             // 合并js
 81             .pipe(concat(‘main.min.js‘))
 82             // 压缩js
 83             .pipe(uglify())
 84             .pipe(gulp.dest(‘./build‘));
 85     });
 86 
 87     //js/css压缩发布-首页优化
 88     gulp.task("csstask-min-index",function(){
 89         gulp.src([‘./images/iconfont.css‘,‘./images/l_base.css‘,‘./images/l_module.css‘,‘./images/index.css‘])
 90             .pipe(concat(‘index-min.css‘))
 91             .pipe(gulp.dest(‘./images‘));
 92     });
 93     gulp.task("jstask-min-index",function(){
 94         gulp.src([‘./images/jquery-1.8.3.min.js‘,
 95                     ‘./images/jquery.cookie.js‘,
 96                     ‘./images/svg-min.js‘,
 97                     ‘./images/l_obox.js‘,
 98                     ‘./images/l_module.js‘,
 99                     ‘./images/l_base.js‘,
100                     ‘./images/idangerous.swiper2.7.6.min.js‘,
101                     ‘./images/index.js‘,
102                     ‘./images/templete_nav_search.js‘])
103             .pipe(concat(‘index-min.js‘))
104             .pipe(gulp.dest(‘./images‘));
105     });
106 
107 
108     // ----- css -----
109     gulp.task(‘csstask‘, function() {
110         if (!options.file) {
111             console.log(‘检查全部css‘);
112             console.log(‘运行gulp csstask --file 文件名,查看对应文件错误信息‘);
113 
114             return gulp.src(‘./images/*.css‘)
115                 // css检查
116                 .pipe(csslint())
117                 .pipe(csslint.reporter(‘fail‘));
118 
119         } else {
120             console.log(‘检查css文件: ./images/‘ + options.file);
121             return gulp.src(‘./images/‘ + options.file)
122                 // .pipe(watch(‘./src/images/*.css‘)) // 只重新编译被更改过的文件
123                 // css检查
124                 .pipe(csslint())
125                 .pipe(csslint.reporter());
126 
127             // css私有变量补全
128             // .pipe(prefixer())
129             // css顺序调整
130             // .pipe(csscomb())
131             // .pipe(gulp.dest(‘./build/images‘))
132             // .pipe(gulp.dest(‘./build‘))
133         }
134 
135     });
136 
137 
138     // css压缩发布
139     gulp.task(‘csstask-min‘, [‘csstask‘], function() {
140         return gulp.src(‘./build/*.css‘)
141             //压缩css
142             .pipe(csso())
143             .pipe(gulp.dest(‘./build/‘));
144     });
145 
146 
147     // ----- html 内容替换 -----
148 
149     // html预览监测
150     gulp.task(‘public‘, function() {
151         return gulp.src(‘./static/public/*‘)
152             .pipe(gulp.dest(‘./preview/public‘));
153     });
154 
155     gulp.task(‘contenttask‘, [‘public‘], function() {
156         console.log(‘打包环境: ‘+options.env);
157         return gulp.src(‘./template/**/*.{html,shtml}‘)
158             // .pipe(watch(‘./src/*.{html,shtml}‘)) // 只重新编译被更改过的文件
159             // 替换内容
160 
161         .pipe(gulpif(options.env === ‘dev‘, template(config.dev_template,{‘interpolate‘:/<%=([\s\S]+?)%>/g})))
162             .pipe(gulpif(options.env === ‘pro‘, template(config.pro_template,{‘interpolate‘:/<%=([\s\S]+?)%>/g})))
163             // .pipe(gulpif(options.env === ‘production‘, processhtml()))
164             // 替换引用
165             .pipe(processhtml())
166             .pipe(gulp.dest(‘./build‘))
167 
168             .pipe(gulpif(options.env === ‘dev‘, shell([‘touch <%= siteId %>.site‘], {
169                 templateData: {
170                     siteId: config.testSiteId
171                 }
172             })))
173             .pipe(gulpif(options.env === ‘pro‘, shell([‘touch <%= siteId %>.site‘], {
174                 templateData: {
175                     siteId: config.proSiteId
176                 }
177             })));
178 
179 
180     });
181 
182     gulp.task(‘contenttask-preview‘,[‘public‘],  function() {
183         return gulp.src(‘./static/**/*.{html,shtml}‘)
184             // 替换内容
185             .pipe(template(config.preview_template))
186             // 替换引用
187             .pipe(processhtml())
188             .pipe(fileinclude({
189                 prefix: ‘@@‘,
190                 basepath: ‘@file‘
191             }))
192             .pipe(gulp.dest(‘./preview‘));
193     });
194 
195 
196 
197     gulp.task(‘contenttask-watch‘, [‘public‘], function() {
198         return gulp.src(‘./static/**/*.{html,shtml}‘)
199             .pipe(watch(‘./static/**/*.{html,shtml}‘)) // 只重新编译被更改过的文件
200             // 替换内容
201             .pipe(template(config.debug_template))
202             // 替换引用
203             .pipe(processhtml())
204             .pipe(fileinclude({
205                 prefix: ‘@@‘,
206                 basepath: ‘@file‘
207             }))
208             .pipe(gulp.dest(‘./preview‘));
209     });
210 
211 
212 
213 
214 
215     // ----- 文件操作 -----
216 
217     // 文件清理
218     gulp.task(‘clean‘, function() {
219         return gulp.src([‘./build‘, ‘./preview‘, ‘./*.site‘], {
220                 read: false
221             })
222             .pipe(clean({
223                 force: true
224             }));
225     });
226 
227     gulp.task(‘clean-build‘, function() {
228         return gulp.src([‘./build‘], {
229                 read: false
230             })
231             .pipe(clean({
232                 force: true
233             }));
234     });
235 
236     gulp.task(‘clean-preview‘, function() {
237         return gulp.src([‘./preview‘], {
238                 read: false
239             })
240             .pipe(clean({
241                 force: true
242             }));
243     });
244 
245     // ----- 压缩图片 -----
246 
247     //压缩图片 - imagemin
248     gulp.task(‘imagemin‘, function() {
249         return gulp.src(‘./images/*.{png,jpg,jpeg,gif}‘)
250             .pipe(imagemin({
251                 progressive: true,
252                 svgoPlugins: [{
253                     removeViewBox: false
254                 }],
255                 use: [pngquant({
256                     quality: ‘100‘
257                 })]
258             }))
259             .pipe(gulp.dest(‘./images‘));
260     });
261 
262     //编译less
263 
264 
265     gulp.task("testLess",function(){
266         var combined = combiner.obj([
267             gulp.src("./images/less/*.less"),
268             watch("./images/less/*.less"),
269             // sourcemaps.init(),
270             less(),
271             cssmin(),
272             // sourcemaps.write(‘./maps‘),
273             gulp.dest("./images")
274         ]);
275 
276         combined.on(‘error‘, function(){
277             console.error.bind(console)
278         });
279         return combined;
280      });
281 
282     gulp.task(‘lesstask‘, function() {
283         return gulp.watch(‘./images/less/*.less‘, [‘testLess‘]);
284     });
285 
286     gulp.task("less-build",function(){
287         var changeFileArr = []
288         var fileArr = []
289         if (options.file && typeof(options.file) == ‘string‘) {
290             changeFileArr = options.file.split(‘,‘)
291             for (var i = 0; i < changeFileArr.length; i++) {
292                 if (changeFileArr[i].indexOf(‘/less/‘) > 0) {
293                     fileArr.push(‘../‘ + changeFileArr[i])
294                 }
295             }
296         }
297 
298         var combined = combiner.obj([
299             gulp.src(fileArr),
300             // sourcemaps.init(),
301             less(),
302             cssmin(),
303             // sourcemaps.write(‘./maps‘),
304             gulp.dest("./images")
305         ]);
306 
307         combined.on(‘error‘, function(){
308             console.error.bind(console)
309         });
310         return combined;
311     })
312 
313     gulp.task("lessBuildAll",function(){
314         var combined = combiner.obj([
315             gulp.src("./images/less/*.less"),
316             // sourcemaps.init(),
317             less(),
318             cssmin(),
319             // sourcemaps.write(‘./maps‘),
320             gulp.dest("./images")
321         ]);
322 
323         combined.on(‘error‘, function(){
324             console.error.bind(console)
325         });
326         return combined;
327     })
328 
329     // 开启本地 Web 服务器功能
330     gulp.task(‘webserver-static‘, function() {
331         // 开发预览
332         browserSync.init({
333             port: config.serverPort,
334             server: {
335                 baseDir: ["preview", "./"],
336                 directory: true,
337                 middleware: function(req, res, next) {
338                     var fs = require(‘fs‘);
339                     var ssi = require(‘ssi‘);
340                     var baseDir = ‘./preview/‘;
341                     var pathname = require(‘url‘).parse(req.url).pathname;
342                     var filename = require(‘path‘).join(baseDir, pathname.substr(-1) === ‘/‘ ? pathname + ‘index.html‘ : pathname);
343 
344                     var parser = new ssi(baseDir, baseDir, ‘/**/*.shtml‘,true);
345                     if (filename.indexOf(‘.shtml‘) > -1 && fs.existsSync(filename))
346                         res.end(parser.parse(filename, fs.readFileSync(filename, {
347                             encoding: ‘utf8‘
348                         })).contents);
349                     else
350                         next();
351                 }
352             }
353         });
354 
355         gulp.watch(‘./**/*‘).on("change", browserSync.reload);
356 
357     });
358 
359 
360     // ----- 任务 -----
361 
362     //默认任务
363     gulp.task(‘default‘, function() {
364         gulp.run(‘help‘);
365     });
366 
367     gulp.task(‘help‘, function() {
368         console.log(‘gulp build --env dev          ---测试环境模板打包‘);
369         console.log(‘gulp build --env pro          ---生产环境模板打包‘);
370         console.log(‘gulp debug                    ---本地调试‘);
371         console.log(‘gulp jstask                   ---js文件检查‘);
372         console.log(‘gulp jstask --file 文件名     ---检查js文件‘);
373         console.log(‘gulp csstask                  ---css文件检查‘);
374         console.log(‘gulp csstask --file 文件名    ---检查css文件‘);
375         console.log(‘gulp imagemin                 ---图片压缩‘);
376     });
377 
378     //项目完成提交任务
379     gulp.task(‘build‘, [‘clean-build‘], function(a) {
380         gulp.run(‘contenttask‘);
381         // gulp.run(‘imagemin‘);
382     });
383 
384     gulp.task(‘preview‘, [‘clean-preview‘], function(a) {
385         gulp.run(‘contenttask-preview‘);
386     });
387 
388     gulp.task(‘debug‘, [‘clean-preview‘], function(a) {
389         gulp.run(‘contenttask-watch‘);
390         gulp.run(‘webserver-static‘);
391         gulp.run(‘lessBuildAll‘);
392         gulp.run(‘lesstask‘);
393     });
394 
395     //项目完成提交任务
396     gulp.task(‘build-min‘, [‘clean‘], function() {
397         gulp.run(‘jstask-min‘);
398         gulp.run(‘csstask-min‘);
399         gulp.run(‘contenttask‘);
400         gulp.run(‘imagemin‘);
401     });

 

 

配置前 :安装所有插件

gulpfile.js 文件配置

原文:https://www.cnblogs.com/qiu2841/p/10898533.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!