最近看了下angular辕近,順便就看到了前端自動(dòng)化構(gòu)建工具grunt
Grunt和 Grunt 插件是通過(guò) npm 安裝并管理的珍德,npm是 Node.js 的包管理器。Grunt 0.4.x 必須配合Node.js >= 0.8.0
版本使用。
- 安裝nodejs
brew install node
如果已經(jīng)安裝了nodejs缨睡,請(qǐng)確保當(dāng)前環(huán)境中所安裝的 npm 已經(jīng)是最新版本
sudo npm update -g npm
注:npm是nodejs自帶的包管理工具(類似于maven)和二,不需要再另行安裝了
- 安裝grunt
sudo npm install -g grunt-cli
注:上述命令執(zhí)行完后徘铝,grunt 命令就被加入到你的系統(tǒng)路徑中了,以后就可以在任何目錄下執(zhí)行此命令了。注意惕它,安裝grunt-cli并不等于安裝了 Grunt怕午!Grunt CLI的任務(wù)很簡(jiǎn)單:調(diào)用與Gruntfile在同一目錄中 Grunt。這樣帶來(lái)的好處是淹魄,允許你在同一個(gè)系統(tǒng)上同時(shí)安裝多個(gè)版本的 Grunt郁惜。
- 使用grunt
- 新建文件夾, 如 grunt
- 進(jìn)入文件夾執(zhí)行
npm init
Paste_Image.png
然后可以在文件夾中看到一個(gè)package.json,內(nèi)容如下:
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
注:name不能為grunt, 否則會(huì)報(bào)錯(cuò)
- 安裝grunt插件
npm install <module> --save-dev
此命令不光安裝了<module>甲锡,還會(huì)自動(dòng)將其添加到devDependencies配置段中兆蕉,如下:
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"grunt-test": "file:grunt"
}
}
npm install grunt --save-dev #安裝Grunt最新版本到項(xiàng)目目錄中,并將其添加到devDependencies內(nèi)
npm install grunt-contrib-jshint --save-dev #安裝 JSHint 任務(wù)模塊
- 新建Gruntfile.js文件缤沦,和package.json都位于項(xiàng)目根目錄下
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") %> */\n'
},
build: {
src: 'src/<%= pkg.name %>.js',
dest: 'build/<%= pkg.name %>.min.js'
}
}
});
// 加載包含 "uglify" 任務(wù)的插件虎韵。
grunt.loadNpmTasks('grunt-contrib-uglify');
// 默認(rèn)被執(zhí)行的任務(wù)列表。
grunt.registerTask('default', ['uglify']);
};
以上是使用壓縮插件壓縮和混淆js
- 運(yùn)行g(shù)runt
grunt #在根目錄下執(zhí)行