安装CLI
先将Grunt命令行(CLI)安装到全局环境中。安装时可能须要使用sudo(针对OSX、*nix、BSD等系统中)权限或者做为管理员(对于Windows环境)来执行如下命令。
npm install -g grunt-cli
准备一份新的 使用Grunt 项目
通常须要在你的项目中添加两份文件:package.json 和 Gruntfile
package.json: 此文件被npm用于存储项目的元数据,以便将此项目发布为npm模块。你能够在此文件中列出项目依赖的grunt和Grunt插件,放置于devDependencies配置段内。
Gruntfile: 此文件被命名为 Gruntfile.js ,用来配置或定义任务(task)并加载Grunt插件的。 css
$ npm init 初始化一个package.json配置项
建立一个gruntfile.js文件html
安装Grunt最新版本到项目目录中,并将其添加到devDependencies内:
npm install grunt --save-devjquery
安装须要使用模块
这里举例使用concat拼接js文件的模块
npm install grunt-contrib-concat --save-devgit
对Gruntfile.js文件配置或定义任务(task)并加载Grunt插件的github
module.exports = function (grunt) { // 注意:加载插件以前必定要先安装插件 // 加载concat插件 grunt.loadNpmTasks('grunt-contrib-concat'); // 加载uglify插件 grunt.loadNpmTasks('grunt-contrib-uglify'); // 加载watch插件 grunt.loadNpmTasks('grunt-contrib-watch'); // 加载cssmin插件 grunt.loadNpmTasks('grunt-contrib-cssmin'); // 加载htmlmin插件 grunt.loadNpmTasks('grunt-contrib-htmlmin'); // 配置任务 grunt.initConfig({ // 获取配置信息对象 pkg: grunt.file.readJSON('package.json'), // 链接文件任务 concat: { // 链接文件的选项 options: { // separator: '/*一堆分号*/',//会插入文件之间 banner: '/*! <%= pkg.description %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %> */', }, // 具体的链接动做 dist: { // 要链接的文件列表 src: ["jquery/jquery.js", "jquery/jquery.fullscreen.js", 'js/FullScreen.js', 'js/SecondManager.js', "js/Label.js", "js/Differences.js", "js/Scene.js", "js/StartScene.js", "js/GameScene.js", "js/TimeoutScene.js", "js/CompleteScene.js", "js/Audio.js", "js/Game.js", "js/GameSceneDatas.js", "js/main.js",], // 链接后生成的文件 dest: 'game.js', }, }, // 压缩js文件,也能够链接js文件 uglify: { // 压缩文件的选项 options: { // separator: '/*一堆分号*/',//会插入文件之间 banner: '/* <%= pkg.description %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %> */\r\n', }, // 一个具体的压缩动做 game: { // 配置压缩文件 files: { // 压缩后生成文件:待压缩文件,能够有多个 'game.min.js': ['game.js'] } } }, // 监视文件变化并自动执行任务 watch: { // 一个具体的监视动做 game: { // 要监视的js文件夹里的全部js文件 files: ["js/*.js", "Gruntfile.js"], // 当文件变化时要执行的任务 tasks: ["concat", "uglify"] }, css: { files: ["index.css"], tasks: ["cssmin"] }, html:{ files:["index.html"], tasks:["htmlmin"] } }, // 压缩css文件 cssmin: { // 一个压缩动做 target: { // 配置压缩文件 files: { // 压缩后生成的文件:待压缩列表 'index.min.css': ['index.css'] } } }, htmlmin: { options: { removeComments: true,//删除注释 collapseWhitespace: true//删除空白 }, index: { files: { "index.min.html": "index.html" } } } }); // 添加注册只需使用grunt就会自动执行如下事件,最后开始监听 grunt.registerTask("default",["concat","uglify","cssmin","htmlmin","watch"]); }
grunt 命令行调用npm
或者单个调用grunt htmlminjson
更多信息grunt