gulpfile-dev.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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. browser: "/Applications/Google\ Chrome.app/"
  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(gulp.dest('src/css'))
  76. .pipe(reload({stream:true}))
  77. })
  78. gulp.task('dev_ejs', function() {
  79. return gulp.src('src/tpl/*.ejs')
  80. .pipe(plugins.ejs().on('error', console.log))
  81. .pipe(gulp.dest('src/'))
  82. .pipe(reload({stream:true}))
  83. })
  84. gulp.task('dev_svg', function() {
  85. function renameSvg(p){
  86. p.basename = 'symbols'
  87. }
  88. return gulp.src('src/svg/slice/*.svg')
  89. .pipe(plugins.svgSymbols({templates: ['default-svg']}))
  90. .pipe(plugins.rename(renameSvg))
  91. .pipe(gulp.dest('src/svg'))
  92. .pipe(reload({stream:true}))
  93. })
  94. // 检测 src/img/slice 文件夹,读取图片信息来生成css切片样式
  95. gulp.task('dev_slice2css', function(){
  96. var fs = require('fs')
  97. var path = require('path')
  98. var async = require('gulp-uglify/node_modules/uglify-js/node_modules/async')
  99. var getPixels = require('multi-sprite/node_modules/spritesmith/node_modules/pixelsmith/node_modules/get-pixels')
  100. var ejs = require('gulp-ejs/node_modules/ejs')
  101. var classnameRule = function(fileName, p){
  102. var relPath = path.relative('src/img/slice', path.dirname(p))
  103. var name = win32? path.join(relPath, fileName).replace(/\\/g, '-'):path.join(relPath, fileName).replace(/\//g, '-')
  104. return name
  105. }
  106. var files, data = {}
  107. async.series([
  108. // 1. 文件过滤
  109. function(next){
  110. var glob = require("glob")
  111. files = glob.sync("src/img/slice/**", {nodir:true})
  112. files = files.filter(function(f){
  113. return !~(path.basename(f).indexOf('@'))
  114. })
  115. next(null)
  116. },
  117. // 2. 生成切片数据
  118. function(next){
  119. var arr = data.slice = []
  120. async.eachSeries(files, iterator, callback)
  121. function iterator(f, _next){
  122. getPixels(f, function (err, pixels) {
  123. if(err){return}
  124. arr.push({
  125. filepath: f,
  126. imageurl: path.relative('src/sass', f).split(path.sep).join('/'),
  127. classname: classnameRule.call({}, path.basename(f, path.extname(f)), f),
  128. width: pixels.shape[0],
  129. height: pixels.shape[1]
  130. })
  131. _next(null)
  132. })
  133. }
  134. function callback(err, result){
  135. next(null)
  136. }
  137. },
  138. // 3. 生成css文件
  139. function(next){
  140. var tpl = (function(){/*
  141. // CSS Sprites切片样式
  142. <% slice.forEach(function(e){ %>
  143. %<%= e.classname%> {
  144. width: <%= e.width%>px;
  145. height: <%= e.height %>px;
  146. background-image: url(<%= e.imageurl%>);
  147. background-repeat: no-repeat;
  148. }
  149. <% }) %>
  150. */}).toString().split('\n').slice(1, -1).join('\n')
  151. var css = ejs.render(tpl, data).replace(/^\n/mg, '')
  152. fs.writeFileSync('src/sass/_slice.scss', css)
  153. }
  154. ])
  155. })
  156. gulp.task('default', ['dev_conn'], function(){
  157. gulp.watch('src/img/slice/**', ['dev_slice2css'])
  158. gulp.watch('src/svg/slice/**', ['dev_svg'])
  159. gulp.watch('src/tpl/**', ['dev_ejs'])
  160. gulp.watch('src/sass/**', ['dev_sass'])
  161. gulp.watch('src/img/**', reload)
  162. gulp.watch('src/svg/**', reload)
  163. gulp.watch('src/js/**', reload)
  164. gulp.watch('src/*.html', reload)
  165. })
  166. }