首页 > 技术文章 > Grunt和Gulp的使用

heavyhe 2015-06-02 16:09 原文

 

Grunt和Gulp的使用

 

 

Grunt的使用

 

新建项目GruntFromEmptyWeb

 

 

 

 

 

 

 

新建TypeScript目录:

 

 

在TypeScript目录下右键点击,新建javascript类型的Tastes.ts文件。

 

 

 

保存后,自动生成Tastes.js文件。

 

 

 

 

再创建一个javascript类型的文件Food.ts

 

 

 

同样,保存后,也会生成Food.js文件

 

 

 

 

 

 

配置NPM

 

 

新建NPM 配置文件:

 

 

在package.json中的 添加下面内容:

 

"grunt": "0.4.5",

"grunt-contrib-clean": "0.6.0",

"grunt-contrib-jshint": "0.11.0",

"grunt-contrib-concat": "0.5.1",

"grunt-contrib-uglify": "0.8.0",

"grunt-contrib-watch": "0.6.1"

 

保存后,nuget会自动下载相应的包。

 

 

 

 

 

配置Grunt

 

新建Grunt 配置文件 gruntfile.js

 

 

 

 

 

 

 

module.exports =
					function (grunt) {
        grunt.initConfig({
                clean: ["wwwroot/lib/*", "temp/"],
        });
};

 

 

添加:

grunt.loadNpmTasks("grunt-contrib-clean");

 

 

 

 

 

 

右键 Gruntfile.js,选择任务运行程序资源管理器

 

 

 

 

 

右键单clean,选择运行

 

 

运行结果:

 

添加 contact

 

concat: {
        all: {
                src: ['TypeScript/Tastes.js', 'TypeScript/Food.js'],
                dest:
					'temp/combined.js'
        }
},

 

 

 

添加jshint

 

jshint: {
        files: ['temp/*.js'],
        options: {

					'-W069':
							false,
        }
},

 

 

添加

uglify: {
        all: {
                src: ['temp/combined.js'],
                dest:
					'wwwroot/lib/combined.min.js'
        }
},

 

添加:

grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');

 

 

保存,打开任务运行管理器,运行。

 

 

 

 

 

 

 

 

 

添加:

watch: {
        files: ["TypeScript/*.js"],
        tasks: ["all"]
}

 

 

grunt.loadNpmTasks('grunt-contrib-watch');

 

 

 

这样,在项目打开时,会自动运行。

 

 

 

 

 

 

 

 

 

 

 

Gulp的使用

 

Gulp相对Grunt,简单一些。

 

 

新建项目:

 

 

 

新建NPM配置文件package.json

 

 

 

 

 

 

 

 

新建 gulpfile.js

 

 

添加:

var gulp = require('gulp');
var clean = require('gulp-clean');
var concat = require('gulp-concat');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');

 

 

 

 

 

 

 

 

运行结果:

 

 

 

TypeScript中的代码,合并到combined.min.js中。

 

推荐阅读