---
title: "使用GruntJS构建Web程序 (2)"
author: "zhouyrt"
date: "2013-12-05T07:41:50Z"
tags: []
categories: ["Web前端"]
slug: "gruntjs-web-2"
draft: false
lastmod: "2013-12-05T07:41:50Z"
id: 1985400
url: "https://snandy.iteye.com/blog/1985400"
---

前一篇记录了Grunt的安装，这篇介绍下怎么使用Gruntjs来搭建一个前端项目，然后使用grunt合并，压缩JS文件。

 

大概有如下步骤

 

1. 新建项目Bejs
2. 新建文件package.json
3. 新建文件Gruntfile.js
4. 命令行执行grunt任务

 

 

 

### 一、新建项目Bejs

 

源码放在src下，该目录有两个js文件，selector.js和ajax.js。编译后代码放在dest，这个grunt会自动生成。  
![](http://dl2.iteye.com/upload/attachment/0091/8540/62f0c16c-b8a1-30e7-a956-d0780f042d69.png)  
 

### 二、新建package.json

 

[package.json](https://npmjs.org/doc/json.html)放在根目录下，它包含了该项目的一些元信息，如项目名称、描述、版本号，依赖包等。它应该和源码一样被提交到svn或git。 现在的项目结构如下  
![](http://dl2.iteye.com/upload/attachment/0091/8542/17324ccb-8298-3bd9-963a-a484d20f0324.png)  
 

package.json内容需符合JSON语法规范，如下

 

```
{
  "name": "Bejs",
  "version": "0.1.0",
  "devDependencies": {
    "grunt": "~0.4.0",
    "grunt-contrib-jshint": "~0.1.1",
    "grunt-contrib-uglify": "~0.1.2",
    "grunt-contrib-concat": "~0.1.1"
  }
}
```

 

 

devDependencies中的grunt在前一篇已经安装了，grunt-contrib-jshint/grunt-contrib-uglify/grunt-contrib-concat则没有安装。三个分别对于三个任务（task）

 

- grunt-contrib-jshint js语法检查
- grunt-contrib-uglify 压缩，采用[UglifyJS](http://www.cnblogs.com/snandy/archive/2012/03/03/2377390.html)
- grunt-contrib-concat 合并文件

 

此时，打开命令行工具进入到项目根目录，敲如下命令: npm install  
![](http://dl2.iteye.com/upload/attachment/0091/8544/dc46821e-22b4-3b50-9c0d-32620de80f25.png)  
![](http://dl2.iteye.com/upload/attachment/0091/8546/f6d3fea1-cebf-39b6-8063-58af00cbaf24.png)  
![](http://dl2.iteye.com/upload/attachment/0091/8548/6c6c7103-b60f-3146-9903-7fddcc7ba64c.png)  
 

再查看根目录，发现多了个node\_modules目录，包含了四个子目录，见图  
![](http://dl2.iteye.com/upload/attachment/0091/8550/0a1f21f9-eb3b-36f6-911e-68dd8d52c805.png)  
 

 

### 三、新建文件Gruntfile.js

 

Gruntfile.js也是放在项目根目录下，几乎所有的任务都定义在该文件中，它就是一个普通的js文件，里面可以写任意js代码而不仅局限于JSON。和package.json一样它也要和源码一样被提交到svn或git。  
![](http://dl2.iteye.com/upload/attachment/0091/8552/6115452b-0555-3210-a892-edb2ad9401d5.png)  
 

 

Gruntfile.js由以下内容组成

1. wrapper函数，结构如下，这是Node.js的[典型写法](http://www.cnblogs.com/snandy/archive/2012/03/08/2378441.html)，使用exports公开API
   
   ```
   module.exports = function(grunt) {
     // Do grunt-related things in here
   };
   ```
2. 项目和任务配置
3. 载入grunt插件和任务
4. 定制执行任务

 

该示例完成以下任务

1. 合并src下的文件（ajax.js/selector.js）为domop.js
2. 压缩domop.js为domop.min.js
3. 这两个文件都放在dest目录下

 

最终的Gruntfile.js如下

```
module.exports = function(grunt) {
    // 配置
    grunt.initConfig({
        pkg : grunt.file.readJSON('package.json'),
        concat : {
            domop : {
                src: ['src/ajax.js', 'src/selector.js'],
                dest: 'dest/domop.js'
            }
        },
        uglify : {
            options : {
                banner : '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
            },
            build : {
                src : 'dest/domop.js',
                dest : 'dest/domop.min.js'
            }
        }
    });
    // 载入concat和uglify插件，分别对于合并和压缩
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    // 注册任务
    grunt.registerTask('default', ['concat', 'uglify']);
}; 
```

 

### 四、执行grunt任务

打开命令行，进入到项目根目录，敲 grunt  
![](http://dl2.iteye.com/upload/attachment/0091/8554/be37c4fe-3858-3d44-a404-7a0ca2bd93c2.png)  
 

从打印信息看出成功的合并和压缩并生成了dest目录及期望的文件，这时的项目目录下多了dest，如下  
![](http://dl2.iteye.com/upload/attachment/0091/8556/6ef89a31-6e36-357e-831d-0a73538ce39b.png)  
 

ok，这里介绍了2个常见任务concat和uglify，jshint等没有介绍。Gruntfile.js里的代码也没有一一解读，感兴趣的同学可在gruntjs的[官方文档](http://gruntjs.com/api/grunt)找到。

 

相关：

[Bejs](http://files.cnblogs.com/snandy/Bejs.zip)

[https://npmjs.org/doc/json.html](https://npmjs.org/doc/json.html)

55