Grunt是一個自動化的項目構建工具. 如果你需要重復的執行像壓縮, 編譯, 單元測試, 代碼檢查以及打包發布的任務. 那麼你可以使用Grunt來處理這些任務, 你所需要做的只是配置好Grunt, 這樣能很大程度的簡化你的工作.
如果在團隊中使用Grunt, 你只需要與其他人員約定好使用Grunt應該規避的問題, 就能夠很方便的自動化的處理大部分的常見工作任務, 你所付出的努力幾乎為0.
Grunt和Grunt插件都是通過npm, Node.js包管理器安裝和管理的.
D:>cd nodeTest1 odejs-grunt D:>cd nodeTest1 odejs-grunt pm install -g grunt-cli
這是全局安裝。
D:>cd nodeTest1 odejs-gruntgrunt
將會出現如下錯誤:
grunt-cli: The grunt command line interface. (v0.1.9) Fatal error: Unable to find local grunt. If you're seeing this message, either a Gruntfile wasn't found or grunt hasn't been installed locally to your project. For more information about installing and configuring grunt, please see the Getting Started guide: http://gruntjs.com/getting-started
執行grunt命令,我們發現系統報錯了,提示不能加載本地庫。因為,grunt命令執行,是需要當前目錄中包括package.json和Gruntfile.js兩個文件。
package.json,是npm項目配置文件
Gruntfile.js,是專門用來配置grunt的配置文件
~ D:>express -e nodejs-grunt ~ D:>cd nodejs-grunt && npm install ~ D: odejs-grunt>npm install grunt --save-dev在package.json文件中輸入如下量:
{
name: nodejs-grunt,
version: 0.0.1,
private: true,
scripts: {
start: node app.js
},
dependencies: {
express: 3.2.2,
ejs: *
},
devDependencies: {
grunt: ~0.4.1,
}
}
並在Gruntfile.js文件中輸入如下量(需要新建):
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today(yyyy-mm-dd) %> */
'
},
build: {
src: 'src/<%= pkg.name %>.js',
dest: 'build/<%= pkg.name %>.min.js'
}
}
});
// Load the plugin that provides the uglify task.
grunt.loadNpmTasks('grunt-contrib-uglify');
// Default task(s).
grunt.registerTask('default', ['uglify']);
};
{
name: nodejs-grunt,
version: 0.0.1,
private: true,
scripts: {
start: node app.js
},
dependencies: {
express: 3.2.2,
ejs: *
},
devDependencies: {
grunt: ~0.4.1,
grunt-contrib-uglify: ~0.1.1
}
}
繼而,再在nodejs-grunt目錄下創建src和build,和nodejs-grunt.js的文件,其中nodejs-grunt.js
var sayHello=function(name) {
return 你好 + name;
}
為確保依賴庫被加載,需要再次執行npm install 命令
接著執行:
D: odejs-grunt>grunt控制台輸入如下:
Running uglify:build (uglify) task File build/nodejs-grunt.min.js created. Uncompressed size: 59 bytes. Compressed size: 40 bytes gzipped (43 bytes minified). Done, without errors.打開nodejs-gruntuild odejs-grunt.min.js
/*! nodejs-grunt 2014-09-08 */
var sayHello=function(l){returnhello +l};
這是一個壓縮實例。
下面將demo放到資源中供大家免費下載
http://download.csdn.net/detail/zz410675629/7881187
參考文章:http://blog.fens.me/nodejs-grunt-intro/