gulpfile-dev.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. module.exports = function(gulp, plugins) {
  2. var argv = require('yargs').argv,
  3. chalk = require('chalk'),
  4. moment = require('moment'),
  5. browserSync = require('browser-sync'),
  6. reload = browserSync.reload,
  7. log = console.log;
  8. //var uncss = require('gulp-uncss-task');
  9. var win32 = process.platform === 'win32';
  10. var that = this;
  11. that.port = +argv.p || 3000;
  12. var pkg = require('../package.json');
  13. var banner = '/*!' + '\n * @project : ' + pkg.name + '\n * @version : ' + pkg.version + '\n * @author : ' + pkg.author + '\n * @update : ' + moment().format('YYYY-MM-DD h:mm:ss a') + '\n */\r';
  14. gulp.task('dev_conn', function() {
  15. browserSync({
  16. ui:false,
  17. server: {
  18. baseDir: "src",
  19. directory: true
  20. },
  21. notify: false,
  22. ghostMode:false,
  23. port: that.port,
  24. open: "external"
  25. },function(err, arg){
  26. if (argv.q) {
  27. var url = arg.options.get('urls').get('external')
  28. var qrcode = require('qrcode-terminal')
  29. qrcode.generate(url);
  30. }
  31. })
  32. })
  33. gulp.task('dev_sass', function() {
  34. function sassCompile4win(){
  35. function normalizeErr(err){
  36. var path = require('path')
  37. var cwd = path.join(__dirname, '..')
  38. var relativePath = path.relative(cwd, err.file)
  39. return relativePath+' @'+err.line+':'+err.column+'\n'+err.message
  40. }
  41. var config = {
  42. onError: function(err){
  43. return plugins.notify().write(normalizeErr(err))
  44. }
  45. }
  46. return plugins.sass(config)
  47. }
  48. function sassCompile4nix(){
  49. function handler(){
  50. return plugins.notify.onError({
  51. title:'sass编译错误',
  52. message:'<%=error.message%>'
  53. })
  54. }
  55. return plugins.sass().on('error', handler())
  56. }
  57. // `gulp -n` 不启用sourcemap
  58. if(argv.n){
  59. return gulp.src('src/sass/*.scss')
  60. .pipe(plugins.cached('sass', {optimizeMemory: true}))
  61. .pipe(win32? sassCompile4nix() : sassCompile4nix())
  62. .pipe(plugins.autoprefixer({browsers: ['> 0%']}))
  63. .pipe(plugins.remember('sass'))
  64. .pipe(gulp.dest('src/css'))
  65. .pipe(reload({stream:true}))
  66. }
  67. return gulp.src('src/sass/*.scss')
  68. .pipe(plugins.plumber())
  69. .pipe(plugins.sourcemaps.init())
  70. .pipe(win32? sassCompile4nix() : sassCompile4nix())
  71. .pipe(plugins.sourcemaps.write({includeContent: false, sourceRoot: '../sass/'}))
  72. .pipe(plugins.sourcemaps.init({loadMaps: true}))
  73. .pipe(plugins.autoprefixer( {browsers: ['> 0%']} ))
  74. .pipe(plugins.sourcemaps.write({includeContent: false, sourceRoot: '../sass/'}))
  75. //.pipe(uncss({
  76. // html: 'http://172.26.35.16:3000/index.html'
  77. //}))
  78. .pipe(gulp.dest('src/css'))
  79. .pipe(reload({stream:true}))
  80. })
  81. gulp.task('dev_ejs', function() {
  82. return gulp.src('src/tpl/*.ejs')
  83. .pipe(plugins.ejs().on('error', console.log))
  84. .pipe(gulp.dest('src/'))
  85. .pipe(reload({stream:true}))
  86. })
  87. // 检测 src/slice 文件夹,读取图片信息来生成css切片样式
  88. gulp.task('dev_slice2css', function(){
  89. var fs = require('fs')
  90. var path = require('path')
  91. var async = require('uglify-js/node_modules/async')
  92. var getPixels = require('get-pixels')
  93. var ejs = require('ejs')
  94. var classnameRule = function(fileName, p){
  95. var relPath = path.relative('src/slice', path.dirname(p))
  96. var name = win32? path.join(relPath, fileName).replace(/\\/g, '-'):path.join(relPath, fileName).replace(/\//g, '-')
  97. return name
  98. }
  99. var files, data = {}
  100. async.series([
  101. // 1. 文件过滤
  102. function(next){
  103. var glob = require("glob")
  104. files = glob.sync("src/slice/**", {nodir:true})
  105. files = files.filter(function(f){
  106. return !~(path.basename(f).indexOf('@'))
  107. })
  108. next(null)
  109. },
  110. // 2. 生成切片数据
  111. function(next){
  112. var arr = data.slice = []
  113. async.eachSeries(files, iterator, callback)
  114. function iterator(f, _next){
  115. getPixels(f, function (err, pixels) {
  116. if(err){return}
  117. arr.push({
  118. filepath: f,
  119. imageurl: path.relative('src/sass', f).split(path.sep).join('/'),
  120. classname: classnameRule.call({}, path.basename(f, path.extname(f)), f),
  121. width: pixels.shape[0]+'px',
  122. height: pixels.shape[1]+'px'
  123. })
  124. _next(null)
  125. })
  126. }
  127. function callback(err, result){
  128. next(null)
  129. }
  130. },
  131. // 3. 生成css文件
  132. function(next){
  133. var tpl = (function(){/*
  134. // CSS Sprites切片样式
  135. <% slice.forEach(function(e){ %>
  136. %<%= e.classname%> {
  137. width: <%= e.width%>;
  138. height: <%= e.height %>;
  139. background-image: url(<%= e.imageurl%>);
  140. background-repeat: no-repeat;
  141. }
  142. <% }) %>
  143. */}).toString().split('\n').slice(1, -1).join('\n')
  144. var css = ejs.render(tpl, data).replace(/^\n/mg, '')
  145. fs.writeFileSync('src/sass/_slice.scss', css)
  146. }
  147. ])
  148. })
  149. gulp.task('default', ['dev_conn'], function(){
  150. gulp.watch('src/slice/**', ['dev_slice2css'])
  151. gulp.watch('src/tpl/**', ['dev_ejs'])
  152. gulp.watch('src/sass/**', ['dev_sass'])
  153. gulp.watch('src/img/**', reload)
  154. gulp.watch('src/js/**', reload)
  155. gulp.watch('src/*.html', reload)
  156. gulp.watch('src/mock/*.js', reload)
  157. })
  158. }