基于Grunt的版本号构建系统新手教程

  作者:zhanhailiang 日期:2014-10-12

1. 安装nodejs,npm,grunt-cli。參见《Windows环境下安装nodejs+npm+grunt-cli工具》。

2. 新建測试项目文件夹例如以下:


当中各文件模板例如以下:

src/index.js

var a = 1;
var b = 2;
 
function test() {
    alert(1);
}
 
var test2 = function() {
    return 3;
};
 
test();
test2();

package.json(入门学习可先使用该模板)

{
  "name": "test",
  "version": "1.0.0",
  "description": "test",
  "author": "",
  "dependencies": {},
  "devDependencies": {
 
  }
}

Gruntfile.js(实现js压缩构建任务)

module.exports = function(grunt) {
    // 配置
    grunt.initConfig({
        pkg : grunt.file.readJSON('package.json'),
        uglify : {
            build : {
                src : 'src/index.js',
                dest : 'dest/index.min.js'
            }
        }
    });
    grunt.loadNpmTasks('grunt-contrib-uglify');
    // 注冊默认任务
    grunt.registerTask('default', ['uglify']);
}; 

3. 在当前測试项目根文件夹下运行npm install grunt-contrib-uglify –save-dev安装对应依赖模块(注: –save-dev将依赖模块自己主动更新到package.json文件里):


4. 在当前測试文件夹下运行grunt构建任务实现版本号构建任务:


5. 至此版本号任务构建就算完毕了。能够注意到在dest文件夹下生成对应的压缩文件:


由此简单教程可对应实现CSS压缩,html压缩,图片压缩等相关版本号构建任务。

总之,grunt的功能相当强大,兴许笔者将会陆续分享关于grunt更具体的教程。

參考文档

附录

推荐使用grunt-init工具来自己主动创建项目,眼下官方维护下面列表的模板

  1. grunt-init-commonjs - Create a commonjs module, including Nodeunit unit tests.
  2. grunt-init-gruntfile - Create a basic Gruntfile.
  3. grunt-init-gruntplugin - Create a Grunt plugin, including Nodeunit unit tests.
  4. grunt-init-jquery - Create a jQuery plugin, including QUnit unit tests.
  5. grunt-init-node - Create a Node.js module, including Nodeunit unit tests.
posted @ 2016-01-21 12:54  phlsheji  阅读(487)  评论(0编辑  收藏  举报