NodeJs Gulpによる構成例

74665 ワード

'use strict';

const gulp = require('gulp');
//const jshint = require('jshint');
const $ = require('gulp-load-plugins')();
const del = require('del');
const merge = require('merge-stream');
const runSequence = require('run-sequence');
const amdOptimize = require('amd-optimize');
const argv = require('minimist')(process.argv.slice(2));
const fs = require('fs');

//     
const RELEASE = !!argv.release;             //              
const DEMO = !!argv.demo;                   //      Demo  
const AUTOPREFIXER_BROWSERS = [             // autoprefixer   
    'ie >= 10',
    'ie_mob >= 10',
    'ff >= 30',
    'chrome >= 34',
    'safari >= 7',
    'opera >= 23',
    'ios >= 7',
    'android >= 4.4',
    'bb >= 10'
];
console.log('release =', RELEASE);
console.log('demo =', DEMO);

const src = {
    assets: 'assets/**/*',
    images: 'images/**/*',
    pages: 'pages/**/*',
    data: 'data/**/*',
    styles: ['styles/bootstrap.less', 'styles/partials/**/*.{css,less}', 'styles/**/**'],
    scripts: ['scripts/**/*.js', '!scripts/**/*.min.js', 'scripts/**/*.min.js', 'scripts/**/*.json', 'scripts/**/**']
};

const pkgs = require('./package.json').dependencies;

gulp.task('default', ['server'], function () {
    gulp.start('help');
});

//   
gulp.task('clean', del.bind(null, ['build/*'], {dot: true}));

//        
gulp.task('vendor', function () {
    return merge(
        gulp.src('node_modules/jquery/dist/*.*')
            .pipe(gulp.dest('build/js/vendor/jquery')),
        gulp.src('node_modules/bootstrap/dist/js/*.*')
            .pipe(gulp.dest('build/js/vendor/bootstrap'))
    );
});

//       
gulp.task('assets', function () {
    return gulp.src(src.assets)
        .pipe(gulp.dest('build'));
});

//   
gulp.task('images', function () {
    return gulp.src(src.images)
        .pipe($.plumber({errorHandler: $.notify.onError('images Error: ')}))
        //.pipe($.cache($.imagemin({
        //    progressive: true,
        //    interlaced: true
        //})))
        //.pipe($.imagemin({
        //    progressive: true,
        //    interlaced: true
        //}))
        .pipe($.changed('build/images'))
        .pipe(gulp.dest('build/images'));
});

//   
gulp.task('fonts', function () {
    return gulp.src('node_modules/bootstrap/fonts/**')
        .pipe(gulp.dest('build/fonts'));
});

//        
gulp.task('onlinehelp', function () {
    return gulp.src('onlinehelp/**/*.*')
        .pipe(gulp.dest('build/onlinehelp'));
});

// HTML   
gulp.task('pages', function () {
    return gulp.src(src.pages)
        .pipe($.plumber({errorHandler: $.notify.onError('pages Error: ')}))
        .pipe($.ejs({}, {ext: '.html'}))
        .pipe($.changed('build', {extension: '.html'}))
        .pipe(gulp.dest('build'));
});

// CSS   
gulp.task('styles-base', function () {
    return gulp.src('styles/bootstrap.less')
        //return gulp.src(src.styles[0])
        .pipe($.plumber({errorHandler: $.notify.onError('styles Error: ')}))
        .pipe($.if(!RELEASE, $.sourcemaps.init()))
        .pipe($.less())
        .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
        .pipe($.csscomb())
        .pipe(RELEASE ? $.cssmin() : $.util.noop())
        //.pipe($.cssmin())
        .pipe($.rename('style.css'))
        //.pipe($.if(!RELEASE, $.sourcemaps.write()))
        .pipe($.changed('build/css', {extension: '.less'}))
        .pipe(gulp.dest('build/css'));
});
gulp.task('styles', function () {
    //return gulp.src('styles/bootstrap.less')
    return gulp.src(src.styles[1])
        .pipe($.plumber({errorHandler: $.notify.onError('styles Error: ')}))
        //.pipe($.if(!RELEASE, $.sourcemaps.init()))
        .pipe($.less())
        .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
        .pipe($.csscomb())
        .pipe(RELEASE ? $.cssmin() : $.util.noop())
        //.pipe($.cssmin())
        //.pipe($.rename('style.css'))
        //.pipe($.if(!RELEASE, $.sourcemaps.write()))
        .pipe($.changed('build/css/partials', {extension: '.less'}))
        .pipe(gulp.dest('build/css/partials'));
});

// JavaScript
gulp.task('scripts', function () {
    return gulp.src(src.scripts.slice(0, 1))
        //.pipe(jshint()) //   js    
        //.pipe(jshint.reporter('default')) //  js        
        .pipe($.plumber({errorHandler: $.notify.onError('scripts Error: ')}))
        //.pipe($.if(!RELEASE, $.sourcemaps.init()))
        .pipe($.if(RELEASE, $.uglify({mangle: false})))
        //.pipe($.rename({suffix:'.min'}))
        //.pipe($.if(!RELEASE, $.sourcemaps.write()))
        .pipe($.changed('build/js'))
        .pipe(gulp.dest('build/js'));
});
gulp.task('unscripts', function () {
    return gulp.src(src.scripts.slice(2))
        .pipe($.plumber({errorHandler: $.notify.onError('unscripts Error: ')}))
        //.pipe($.if(!RELEASE, $.sourcemaps.init()))
        //.pipe($.if(RELEASE, $.uglify({ mangle: false })))
        //.pipe($.if(!RELEASE, $.sourcemaps.write()))
        .pipe($.changed('build/js'))
        .pipe(gulp.dest('build/js'));
});

// Build
gulp.task('build', ['clean'], function (cb) {
    if (DEMO) {
        runSequence(['pages', 'assets', 'vendor', 'images', 'fonts', 'styles-base', 'styles', 'unscripts', 'scripts', 'MockData', 'onlinehelp'], cb);
    } else {
        runSequence(['pages', 'assets', 'vendor', 'images', 'fonts', 'styles-base', 'styles', 'unscripts', 'scripts', 'onlinehelp'], cb);
    }
});

// MockData
gulp.task('MockData', function () {
    let baseUrl = 'data';
    let appendData = '';
    let mockJsFile = './scripts/plugins/mockData/MockData.js';
    let files;
    fs.writeFileSync(mockJsFile, 'define( [ \'plugins/mockData/mock-min\'], function (Mock) {
' + 'var errorData = {"success": false,"data": null,"failCode": 404,"params": null,"message": " "};
', 'utf8'); // if (fs.existsSync(baseUrl)) { // files = fs.readdirSync(baseUrl); for (var i = 0, fileLen = files.length; i < fileLen; i++) { var _thisFile = files[i]; var objName = _thisFile.replace('.js', ''); var requireFile = "./" + baseUrl + "/" + objName; var _thisObj = require(requireFile); for (var item in _thisObj) { var _thisTemplate = _thisObj[item]; if (typeof _thisObj[item] === "object") { _thisTemplate = JSON.stringify(_thisTemplate); } appendData = 'Mock.mock("/' + objName + '/' + item + '",' + _thisTemplate + ');
'; fs.appendFileSync(mockJsFile, appendData, 'utf8'); } } imageFunc(); var reg = /^\//; fs.appendFileSync(mockJsFile, '
$.ajaxPrefilter(function (options, originalOptions, jqXHR) { if((options.type).toUpperCase() == \'GET\'){options.cache = true;} (!(' + reg + '.test(options.url))) && (options.url = "/" + options.url)});
' + '
var tokenId = parseInt(1000000000*Math.random()); ' + '
return {config: {isMock: true,login: function (user) {' + 'tokenId && Cookies.set(\'tokenId\', tokenId);' + 'if (user) {' + 'Cookies.set(\'userName\', user.userName);' + 'Cookies.set(\'loginName\', user.loginName);' + 'Cookies.set(\'userid\', user.userid);' + 'Cookies.set(\'userType\', user.userType);' + '}' + '}}};
});', 'utf8'); //createStreamFile(); } else { console.log(baseUrl + " Not Found!"); } function imageFunc() { var srtImgFun = '
var regArr = [".jpg",".gif",".svg",".png"];' + '//var reg=/^?(\.jpg|\.png|\.gif|\.svg)$/;
' + 'var imgs= $("img");' + 'if(imgs.length){' + '$.each(imgs,function(index,item){' + 'var thisImgSrc = $(item).attr("src");' + 'console.log(thisImgSrc);' + 'var thisImgSrcType = $(item).attr("src").slice(-4);' + 'if(thisImgSrcType.indexOf(regArr)<0){' + '$.get(thisImgSrc,function(result){' + 'console.log(result);' + 'var data = JSON.parse(result);' + '$(item).attr("src",data.imageUrl);' + '/*$(item).attr("src", eval(result));*/' + '})' + '}' + '}' + ')}'; fs.appendFileSync(mockJsFile, srtImgFun, 'utf8'); } }); // BrowserSync gulp.task('server', ['build'], function () { var path = require('path'); var url = require('url'); var fs = require('fs'); var browserSync = require('browser-sync'); var proxyMiddleware = require('http-proxy-middleware'); var Mock = require('mockjs'); var uuid = require('uuid'); var middleware = []; var isMock = DEMO; if (isMock) { middleware = function (req, res, next) { var urlObj = url.parse(req.url, true), method = req.method, query = urlObj.query, mockUrl; var body = ''; req.on('data', function (data) { body += data; }); req.on('end', function () { if (urlObj.pathname.match(/\..+$/) || urlObj.pathname.match(/\/$/)) { next(); return; } body = body || JSON.stringify(query); console.log('[requist] ', method, urlObj.pathname, body); var dataUrl = 'data'; var pathTree = urlObj.pathname.split('/'); var mockDataFile = path.join(__dirname + path.sep + dataUrl, path.sep + pathTree[1]) + ".js"; //file exist or not fs.access(mockDataFile, fs.F_OK, function (err) { var isImage = req.headers.accept.indexOf('image') != -1; if (err) { var c = { "success": false, "data": null, "failCode": 404, "params": null, "message": " ", "notFound": mockDataFile }; //console.log('[response] ', c); res.setHeader('Content-Type', (isImage ? 'image/*' : 'application/json')); res.end(JSON.stringify(c)); next(); return; } try { delete require.cache[require.resolve(mockDataFile)]; var data = require(mockDataFile) || {}; var result, mockUrl = pathTree[2]; if (data[mockUrl] && typeof data[mockUrl] === "object") { result = Mock.mock(data[mockUrl]); } else if (typeof data[mockUrl] === 'function') { var options; try { options = {body: JSON.parse(body)}; } catch (e) { options = {body: JSON.parse('{"' + body.replace(/=/g, '":"').replace(/&/g, '","') + '"}')}; } result = Mock.mock(data[mockUrl](options || {})); } isImage && (result = Mock.Random.image(data[mockUrl])); res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Content-Type', (isImage ? 'image/*' : 'application/json')); res.setHeader('tokenId', uuid.v1()); var s = result || { "success": false, "data": null, "failCode": 0, "params": null, "message": null }; //console.log('[response] ', JSON.stringify(s)); res.end(JSON.stringify(s) || s); } catch (e) { console.error(e); } }); }); //next(); }; } else { var host = 'http://127.0.0.1:8080'; middleware = [ proxyMiddleware(['/app'], {target: host, changeOrigin: true}) ]; } browserSync({ //files: '/build/**', // open: false, // 'external' URL, 'local' URL //https: true, port: 80, online: false, notify: false, logLevel: "info", logPrefix: "iems mock", logConnections: true, // logFileChanges: true, // scrollProportionally: false, // ghostMode: { clicks: false, forms: false, scroll: false }, server: { baseDir: './build', middleware: middleware } }); gulp.watch(src.assets, ['assets']); gulp.watch(src.images, ['images']); gulp.watch(src.pages, ['pages']); gulp.watch(src.data, ['MockData']); gulp.watch(src.styles, ['styles-base', 'styles']); //gulp.watch(src.styles[2], ['styles']); gulp.watch(src.scripts[4], ['unscripts', 'scripts']); gulp.watch('./build/**/*.*', function (file) { browserSync.reload(path.relative(__dirname, file.path)); }); }); gulp.task('help', function () { console.log(' gulp build '); console.log(' gulp assets '); console.log(' gulp images '); console.log(' gulp pages html( ) '); console.log(' gulp styles cssless'); console.log(' gulp scripts JavaScript '); console.log(' gulp help gulp '); console.log(' gulp server server'); console.log(' gulp --demo DEMO '); console.log(' gulp --deploy ( )'); console.log(' gulp --release '); });