静态页打包中 grunt使用,并通过shell指令一键打包发布

 

场景:纯静态页面,技术架构 html+js+zepto.js

该项目痛点:

源码修改后,打包过程需要完成多步骤工作:

1.旧包删除。  grunt-contrib-clean

2.静态页中引入文件的版本号更新。  grunt-replace

3.复制源码文件到打包目录。  grunt-contrib-copy

4.将源码文件中的环境参数js文件,并与业务临死文件合并,生成各环境引入的正式的业务文件。  grunt-contrib-concat

5.废弃文件删除(grunt-contrib-clean)。删除打包目录的临时文件、及环境参数js文件、该环境不存在的文件(有些页面部署在某一个环境下)。

6.压缩正式服pro目录下的js文件;  grunt-contrib-uglify

7.检查修改后,git提交。(尤其是 检查修改 这一步,人工检测费时且容易遗漏,极大地延长了开发时间)

 

目标:希望通过简单的两个shell命令,自动完成以上工作。

 

项目文件结构:


       

 

源码code目录下文件结构如下:

   

 

html文件调用


 

 

 

安装依赖, package.json文件内容如下


{

  "name": "my-project-name",
  "version": "0.1.0",
  "devDependencies": {
    "grunt": "^1.4.1",
    "grunt-contrib-clean": "^2.0.0",
    "grunt-contrib-concat": "^1.0.1",
    "grunt-contrib-copy": "^1.0.0",
    "grunt-contrib-uglify": "^0.5.1",
    "grunt-replace": "^2.0.2",
    "install": "^0.13.0",
    "shelljs": "^0.8.4"
  },
  "scripts": {
    "grunt": "node ./shell-grunt.js",  #npm run grunt   
    "push": "node ./shell.js"  #npm run push
  }
}

 
 

Gruntfile.js内容如下:


 

// 文件版本更新    !!!请在打包前修改此处参数
var versionCheck = /(\.js\?v=20210715)/g; //版本号替换规则   e.g  /(\.js\?v=)(\d)*/g 匹配所有 .js?v=任意数字串 的内容
var versionNew = '.js?v=20210716';  //替换后的版本号内容
var editfiles = ['code/*.html']; //待修改的目录  值为['code/*.html']时,修改范围为code下所有的.html文件
var outputPath = 'code/'; //输入目录 提醒:测试时可用/dist代替,确认替换正则生效后,再使用真实目录
 

// 将pro目录所有js文件压缩为.min.js文件
var proJS = ['active.js','active2.js', ........'video.js']
var uglifyObj = {}; // uglify目录配置
for (var i in proJS) { 
  var jsName = proJS[i].split('.')[0];
  uglifyObj['pro_'+jsName] = { src: 'pro/js/'+proJS[i], dest: 'pro/js/'+jsName+'.min.js' };
 
 
module.exports = function(grunt) {
  
  grunt.initConfig({
      pkg: grunt.file.readJSON('package.json'),
      clean: { //清除目标文件下文件
        // 打包前 清空旧数据
        start:{ src: ["exp/","pre/","ios/","pro/"] },
 
        // 打包后 清除重要文件(不可暴露api地址给外网)
        // 东胜相关js环境文件
        end:{ src: ["exp/api/","pre/api/","ios/api/","pro/api/", "exp/js/utils0.js","pre/js/utils0.js","ios/js/utils0.js","pro/js/utils0.js"] },
 
      },
      replace: {
        dist: {  //打包前,替换code下修改过的文件版本号
          // options: {patterns: [{ match: '/(\.js\?v=)(\d)*/g', replacement: 'bar' }]},
          options: {patterns: [{ match: versionCheck, replacement: versionNew }]}, 
          files: [{ expand: true, flatten: true, src: editfiles, dest: outputPath }]
        }, 
        pro: {  //打包后,替换pro目录html文件中js引入版本号
          options: {patterns: [{ match:  /(\.js\?v=)/g, replacement: '.min.js?v=' }]},
          files: [{ expand: true, flatten: true, src: ['pro/*.html'], dest: 'pro/' }]
        },   
        console_exp: {  //打包完成后,去掉exp目录下vconsole启用的debugger=1判断条件
          // options: {patterns: [{ match: /(\.js\?v=)(\d)*/g, replacement: 'bar' }]},
          options: {patterns: [{ match: /location.href.indexOf\(\'debugger=1\'\)>-1/, replacement: true }]},
          files: [{ expand: true, flatten: true, src: ['exp/*.html'], dest: 'exp/' }]
        }
 
      },
 
      // 复制code目录下所有文件及目录到exp目录下
      //cwd复制相对路径,最终文件移动到特定路径    flatten:设置(true、false)用来指定是否保持文件目录结构
      copy: {
        exp:{  files: [{ expand: true, cwd: 'code', src: '**', dest: 'exp/' }]  },
        pre:{  files: [{ expand: true, cwd: 'code', src: '**', dest: 'pre/' }]  },
        ios:{  files: [{ expand: true, cwd: 'code', src: '**', dest: 'ios/' }]  },
        pro:{  files: [{ expand: true, cwd: 'code', src: '**', dest: 'pro/' }]  }
      },
 
      // 合并功能
      concat: {
        // 东胜utils.js文件环境参数加入
        code: { src: ['code/api/env-code.js', 'code/js/utils0.js'], dest: 'code/js/utils.js' },
        exp: { src: ['exp/api/env-exp.js', 'exp/js/utils0.js'], dest: 'exp/js/utils.js' }
      },
 
      // 压缩功能
      uglify: uglifyObj
    });

 // 插件引入
    // 加载 清除文件 插件
    grunt.loadNpmTasks('grunt-contrib-clean');
    // 加载 替换内容 插件
    grunt.loadNpmTasks('grunt-replace');
    // 加载 合并文件 插件
    grunt.loadNpmTasks('grunt-contrib-concat');
    // 加载 压缩文件 的插件
    grunt.loadNpmTasks('grunt-contrib-uglify');
    // 加载复制的插件
    grunt.loadNpmTasks('grunt-contrib-copy');
 grunt 执行语法格式:
  //写法一:带注释
    // 打包初始化 删除所有打包目录
    grunt.registerTask('del', '删除所有打包目录', function(){
      grunt.log.writeln('删除所有打包目录...');
      grunt.task.run( ['clean','XXX']);
    });
 
  //写法二:不带注释
    grunt.registerTask('del',['clean','XXX'])
 

/*
  注意 全环境打包步骤(已通过shell-grunt.js设置自动执行,执行#npm run grunt即可):

  1.更新版本号。修改该文件顶部的versionCheck、versionNew、editfiles,以更新code目录版本号及修改文件范围参数 。执行更新版本号命令 #grunt reVersion

  2.打包东胜落地页
  # grunt default

  3.打包红幺鸡落地页
  #grunt main

  4.删除各环境废弃的js/main0.js文件 # grunt delall

  5.压缩pro目录文件 minjs
  
*/

 
 
 
shell-grunt.js (用于打包) 内容如下:

 
// 当前grunt环境打包并提交  通过命令 #npm run push 来执行该文件

// shell安装    # npm install [-g] shelljs
// //局部模式
// var shell = require('shelljs');
// 全局模式下,就不需要用shell开头了。

var shell = require("shelljs");
// var exec = shell.exec;

shell.echo('注意:打包前,请到Gruntfile.js顶部更新/code目录下相关css及js文件版本号。');

if (!shell.which('grunt')) {
    shell.echo('Sorry, this script requires grunt');
    shell.exit(1);
}

shell.exec('grunt reVersion');    //更新版本号
shell.exec('grunt');    //打包东胜落地页
shell.exec("grunt main")    //打包红幺鸡落地页
shell.exec("grunt delall"); //删除所有中转文件 js/utils0.js js/main0.js
shell.exec("grunt minjs"); //压缩正式服文件
 

// 使用node执行或者package.json中封装一下
// //在package.json中封装
// {
//   "private": true,
//   "scripts": {
//     "grunt": "node shell-grunt.js",
//     }
// }
// 调用方式一:使用node直接指定
// node shell-grunt.js
// //调用方式二:运行
// npm run grunt


 
shell.js(用于git提交) 内容如下:

// 当前grunt环境打包并提交  通过命令 #npm run push -- '自定义commit描述'' 来执行该文件

// shell安装    # npm install [-g] shelljs
// //局部模式
// var shell = require('shelljs');
// 全局模式下,就不需要用shell开头了。

var name = process.argv[2] || 'commit描述';
var shell = require("shelljs");
var exec = shell.exec;

shell.echo('注意:提交代码前,请确保已修改相关css及js文件版本号,并已将/pro 目录下相关js引入改为.min.js版本。');
if (!shell.which('git')) {
    shell.echo('Sorry, this script requires git');
    shell.exit(1);
}

if (exec('git add .').code !== 0) {
  echo('Error: Git add failed');
  exit(1);
}
if (exec(`git commit -m "${name}"`).code !== 0) {
  echo('Error: Git commit failed');
  exit(1);
}
if (exec('git push').code !== 0) {
  echo('Error: Git commit failed');
  exit(1);
}
exec(`echo git success ${name}`);
 

 
README.txt

打包发版操作步骤:
1.去Gruntfile.js顶部修改code目录的css及js版本号;
2.执行打包命令 #npm run grunt (对应shell-grunt.js文件,Gruntfile.js定义打包的所有行为);
3.执行git提交命令 #npm run push -- "本次提交的描述" (对应shell.js文件);


 

 

 

posted @ 2021-07-16 12:16  liuxu_xrl  阅读(225)  评论(0编辑  收藏  举报