玩转npmscript自动化构建 支持ES6 支持POSTCSS(2)

玩转npmscript自动化构建 支持ES6 支持POSTCSS(2)_第1张图片

这次更新去掉了自动刷新浏览器,
如果感觉不爽 可以自行加live-reload 即可

简化了npm命令:
现在npm run create已经不需要了
npm install之后只需npm run dev即可实现监听 和VUE保持一致 便于记忆

自动压缩css并加前缀
支持ES6

使用方法copy成对应的js和json之后
1 npm install
2 npm run dev

package.json

{
  "name": "npm",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "config": {
    "port": 8000,
    "ip": "192.168.123.1"
  },
  "scripts": {
    "css": "postcss -w ./src/css/*.css -d ./dist/css",
    "http": "cd ./dist&&cross-var http-server -c-1 -o -a $npm_package_config_ip -p $npm_package_config_port",
    "js": "uglifyjs ./dist/js/*.js -m -c  -o ./dist/js/main.js",
    "ES6": "babel ./src/js -d ./dist/js -w",
    "html_images_watch": "node html_images_watch.js",
    "dev": "node create.js",
    "dev_Manual": "npm-run-all --parallel css http ES6 html_images_watch"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "autoprefixer": "^7.2.1",
    "babel-cli": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "chalk": "^2.3.0",
    "chokidar": "^1.7.0",
    "cross-var": "^1.1.0",
    "cssnano": "^3.10.0",
    "filedir": "^1.0.1",
    "http-server": "^0.10.0",
    "npm-run-all": "^4.1.2",
    "postcss-cli": "^4.1.1",
    "shelljs": "^0.7.8",
    "uglify-js": "^3.2.1"
  },
  "dependencies": {
    "art-template": "^4.12.2"
  }
}

html_images_watch.js

var chokidar = require('chokidar');
var filedir=require("filedir");
var path = require("path");
var fs = require("fs");
var shell = require('shelljs');
var chalk=require("chalk")

function copy_(src,type,target){
    var filePath = path.resolve();
    var fileArr = [];

    
    fs.readdir(src,function(err,files){
        if(err){
            console.log(err);
            return;
        }
        files.forEach(function(filename){   //提取所有html文件
            if(getdir(filename) == type){
                 fileArr.push(filename)
               }
         });
         fileArr.forEach(function(el){     //把所有html复制进dist
    
            filedir.copy(src+"/"+el, target+el)
         })
         
    });

}


var watcher = chokidar.watch('./src', {
  ignored: /[\/\\]\./, persistent: true
});

var log = console.log.bind(console);

function getdir(url){
    var arr = url.split('.');
    var len = arr.length;
    return arr[len-1];
}

watcher
  .on('add', function(path) { 
        console.log(chalk.yellow("您添加了"+path+"文件"))
        if(getdir(path)=="html"){ //如果添加了html文件
            copy_("./src","html","./dist/")
        } 
        if(getdir(path)=="jpg"){ //如果添加了html文件
           
            if(path.split("\\")[1]!="images"){
                console.log(chalk.red("图片应该放进images文件夹内,故这次添加文件失败"))
            }
            copy_("./src/images","jpg","./dist/images/")
        } 
        if(getdir(path)=="png"){ //如果添加了html文件
            if(path.split("\\")[1]!="images"){
                console.log(chalk.red("图片应该放进images文件夹内,故这次添加文件失败"))
            }
            copy_("./src/images","png","./dist/images/")
        }
        if(getdir(path)=="gif"){ //如果添加了html文件
            if(path.split("\\")[1]!="images"){
                console.log(chalk.red("图片应该放进images文件夹内,故这次添加文件失败"))
            }
            copy_("./src/images","gif","./dist/images/")
        }
        if(getdir(path)=="jpeg"){ //如果添加了html文件
            if(path.split("\\")[1]!="images"){
                console.log(chalk.red("图片应该放进images文件夹内,故这次添加文件失败"))
            }
            copy_("./src/images","jpeg","./dist/images/")
        }
        if(path.split("\\")[1]=="lib"){
          
            copy_("./src/lib","js","./dist/lib/")
         }
        
   })
  .on('addDir', function(path) { 
      
   })
  .on('change', function(path) { 
    console.log(chalk.yellow("您改变了"+path+"文件"))  
    
    if(getdir(path)=="html"){ //如果添加了html文件
        copy_("./src","html","./dist/")
    } 

     if(path.split("\\")[1]=="lib"){
    
        copy_("./src/lib","js","./dist/lib/")
     }



   })
  .on('unlink', function(path) { 
      console.log(chalk.yellow("您删除了"+path));
      if(getdir(path)=="html"){ //如果删除了html文件
          var file_name=path.split("\\")[0]
          filedir.del('./dist/'+file_name)
      }

      if(getdir(path)=="jpg"||getdir(path)=="png"||getdir(path)=="gif"||getdir(path)=="jpeg"){ 
        var file_name=path.split("\\")[2]

        filedir.del('./dist/images/'+file_name)
      }


       if(path.split("\\")[1]=="lib"){
            var file_name=path.split("\\")[2]
            filedir.del('./dist/lib/'+file_name);
  
         }
         if(path.split("\\")[1]=="js"){
            var file_name=path.split("\\")[2]
           
            filedir.del('./dist/js/'+file_name);
  
         }
      
  })


  .on('unlinkDir', function(path) { 
      
  })
  .on('error', function(error) { log('Error happened', error); })
  .on('ready', function() { 
    console.log(chalk.yellow("欢迎使用,一切准备就绪")) 
   })
  .on('raw', function(event, path, details) { })

create.js

// // 创建目录,支持多级创建
// filedir.mkdir('D:/filedirTest');
// // 删除文件或目录
// filedir.del('D:/filedirTest');
// // 复制文件
// filedir.copy('D:/a.txt', 'D:/b.txt');
// // 读文本文件
// var text = filedir.read('D:/filedirTest.txt');
// // 写文本文件
// filedir.write('D:/filedir_write.txt', '0123456789');
// // JSON变量写出到json文件,若目录不存在则自动创建
// filedir.writeJsonFile('D:/filedir_write.txt', {Color:'Blue'});
// // 判断文件或目录是否存在
// filedir.isExist('D:/filedir_write.txt');
// // 判断是不是一个已存在的文件
// filedir.isFile('D:/filedirTest');
// // 判断是不是一个已存在的目录
// filedir.isDir('D:/filedirTest');


var http = require('https')
var filedir=require("filedir");
var path = require("path");
var shelljs=require("shelljs")
var chalk=require("chalk")
var port=8000
//console.log($npm_package_config_ip)
var jquery_url="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"

function get_js(url,address){
    http.get(url, function (response) {
        response.setEncoding('binary');  //二进制binary
        var Data = '';
        response.on('data', function (data) {    //加载到内存
            Data += data;
        }).on('end', function () {          //加载完
            filedir.write(address, Data );
        })
      })

}
//
function get_arttemplate(){
    var arttemplate = filedir.read('./node_modules/art-template/lib/template-web.js')
    filedir.write('./src/lib/arttemplate.js',arttemplate)
}
var Prompt={
    dist:{src:"./dist",text:"开始创建dist文件夹"},
    dist_css:{src:"./dist/css",text:"开始创建dist/css"},
    dist_images:{src:"./dist/images",text:"开始创建dist/images"},
    dist_js:{src:"./dist/js",text:"开始创建dist/js"},
    dist_lib:{src:"./dist/lib",text:"开始创建dist/lib"},
    dist_index_html:{src:"./dist/index.html",text:"开始创建dist/index.html"},

    src:{src:"./src",text:"开始创建src文件夹"},
    src_css:{src:"./src/css",text:"开始创建src/css"},
    src_images:{src:"./src/images",text:"开始创建src/images"},
    src_js:{src:"./src/js",text:"开始创建src/js"},
    src_lib:{src:"./src/lib",text:"开始创建src/lib"},
    src_index_html:{src:"./src/index.html",text:"开始创建src/index.html"}
}
Object.prototype.hasO=Object.prototype.hasOwnProperty
function judge(){
   var this_=this
   for(var i in this_){
       if(this_.hasO(i)){
           if(!filedir.isDir(this_[i].src)){
             var te_name=this_[i].src.split(".");
             te_name=te_name[te_name.length-1];
             
             var for_css=this_[i].src.split("/")
             for_css=for_css[for_css.length-1]
             if(te_name=="html"&&filedir.isFile(this_[i].src)  ){
                console.log(chalk.yellow("已经有index.html了,不要重复create"))
                 continue
             }
             if(te_name=="html"&&!(filedir.isFile(this_[i].src))  ){   
                console.log(chalk.green(this_[i].text));
                filedir.write(this_[i].src,"Welcome to use")
                continue
             }else{
                console.log(chalk.green(this_[i].text));
                filedir.mkdir(this_[i].src);
             } 
             if(for_css=="css"&&i=="src_css"){
                filedir.mkdir(this_[i].src)
                filedir.write("./src/css/main.css",
                "*{padding:0;margin:0};"+
                "a{text-decoration:none};ul,ol{list-style:none}"+
                 "img{border:none}"+
                 "br{font-size:0;line-height:0;clear:both}"
                 )
             }
             
          }
       }
   }
}
 judge.call(Prompt)


if(!filedir.isFile("./.babelrc")){
    console.log(chalk.green("开始创建.babelrc"))
    filedir.write('./.babelrc',"{\"presets\": [\"env\"],\"plugins\" : [ ]}")
   }
 
if(!filedir.isFile("./postcss.config.js")){
    console.log(chalk.green("开始创建postcss.config.js"))  
    filedir.write("./postcss.config.js","module.exports = {plugins: [require('autoprefixer'),require('cssnano')({preset: 'default' }),],}")
   }
    
if(!filedir.isFile("./http_config.json")){
      console.log(chalk.green("开始创建http_config.json"))
      filedir.write("./http_config.json","{\"port\": "+port+",\"files\": [\"./dist/**/*.{html,htm,css,js}\"],\"server\": { \"baseDir\": \"./dist\" }}")
}



console.log(chalk.cyan(
"-------------------\n"+
"所有文件初始化完毕完毕\n"+
"-------------------\n"
))
console.log(chalk.cyan(
"-------------------\n"+
"开始启动监听Wait three seconds\n"+
"-------------------\n"
    ))
shelljs.exec("npm-run-all --parallel css http ES6 html_images_watch")

你可能感兴趣的:(玩转npmscript自动化构建 支持ES6 支持POSTCSS(2))