gulpfile-dev.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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 pageWidth = argv.w, isProcessREM = !!argv.w, data = {}, files
  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: formatPX(pixels.shape[0]),
  129. height: formatPX(pixels.shape[1]),
  130. cover: isProcessREM?'background-size:cover;':''
  131. })
  132. _next(null)
  133. function formatPX (pxValue) {
  134. if (!pageWidth) {return pxValue+'px'}
  135. if (+pageWidth === 1) { return pxValue*16/720+'rem' }
  136. return (pxValue*16/+pageWidth)+'rem'
  137. }
  138. })
  139. }
  140. function callback(err, result){
  141. next(null)
  142. }
  143. },
  144. // 3. 生成css文件
  145. function(next){
  146. var tpl = (function(){/*
  147. // CSS Sprites切片样式
  148. <% slice.forEach(function(e){ %>
  149. %<%= e.classname%> {
  150. width: <%= e.width%>;
  151. height: <%= e.height %>;
  152. background-image: url(<%= e.imageurl%>);
  153. background-repeat: no-repeat;
  154. <%= e.cover%>
  155. }
  156. <% }) %>
  157. */}).toString().split('\n').slice(1, -1).join('\n')
  158. var css = ejs.render(tpl, data).replace(/^\n/mg, '')
  159. fs.writeFileSync('src/sass/_slice.scss', css)
  160. }
  161. ])
  162. })
  163. gulp.task('default', ['dev_conn'], function(){
  164. gulp.watch('src/img/slice/**', ['dev_slice2css'])
  165. gulp.watch('src/svg/slice/**', ['dev_svg'])
  166. gulp.watch('src/tpl/**', ['dev_ejs'])
  167. gulp.watch('src/sass/**', ['dev_sass'])
  168. gulp.watch('src/img/**', reload)
  169. gulp.watch('src/svg/**', reload)
  170. gulp.watch('src/js/**', reload)
  171. gulp.watch('src/*.html', reload)
  172. })
  173. }