更多实践

gulp

如果我们的框架里没有gulp,会显得有点low,那我们也使用gulp作为构建工具吧

一般作用

  • 构建,打包
  • watch

先实现一个简单的watch吧

  1. npm i -g gulp
  2. npm i -S gulp
  3. npm i -S gulp-watch
  4. npm i -S gulp-mocha

create gulpfile.js

  1. touch gulpfile.js

in gulpfile.js

  1. var gulp = require('gulp');
  2. var watch = require('gulp-watch');
  3. var mocha = require('gulp-mocha');
  4. var source_path = ['test/**/*.js', 'lib/*.js'];
  5. gulp.task('watch', function() {
  6. gulp.watch(source_path, ['mocha']);
  7. });
  8. gulp.task('mocha', function () {
  9. return gulp.src(source_path , {read: false})
  10. // gulp-mocha needs filepaths so you can't have any plugins before it
  11. .pipe(mocha({reporter: 'spec'}));
  12. });

测试

执行一次测试

  1. gulp mocha

如果source_path目录下的文件变动,会触发一次测试(作业依赖)

  1. gulp watch

增加默认gulp命令

  1. gulp.task('default',['mocha', 'watch']);

rails里的rake routes挺爽,不妨实现一些

  1. var mount = require('mount-routes');
  2. gulp.task('routes', function() {
  3. var express = require('express');
  4. var app = express();
  5. // mount routes
  6. mount(app, __dirname + '/app/routes', true);
  7. });

于是

  1. gulp routes

效果基本一样,有木有?

更多之前曾在Stuq微课堂里分享过【Gulp实战和原理解析(以weui作为项目实例)】

http://i5ting.github.io/stuq-gulp/

还有一篇更基础的教程

https://github.com/streakq/js-tools-best-practice/blob/master/doc/Gulp.md

browser-sync

代码变动,浏览器也可以不刷新的

  • browser-sync
  1. gulp.task('less_server',['build_less'] ,function () {
  2. browserSync.init({
  3. proxy: "127.0.0.1:3005"
  4. })
  5. gulp.watch('./public/css/main.less', ['build_less']);
  6. gulp.watch('./public/*.html',function () {
  7. browserSync.reload();
  8. });
  9. });

具体参见【Gulp实战和原理解析(以weui作为项目实例)】

http://i5ting.github.io/stuq-gulp/

open

都是mac闹的,人都变懒了

  1. var express = require('express');
  2. var app = express();
  3. var path = require('path');
  4. var open = require("open");
  5. app.get('/', function (req, res) {
  6. res.send('Hello World')
  7. })
  8. // 随机端口3000 - 10000 之间
  9. app.listen(4001)
  10. open("http://127.0.0.1:4001");