gulpfile-dev.js 6.1 KB

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