安装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插件的。
$ npm init 初始化一个package.json配置项
创建一个gruntfile.js文件
安装Grunt最新版本到项目目录中,并将其添加到devDependencies内:
npm install grunt --save-dev
安装需要使用模块
这里举例使用concat拼接js文件的模块
npm install grunt-contrib-concat --save-dev
对Gruntfile.js文件配置或定义任务(task)并加载Grunt插件的
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") %> */ ', }, // 一个具体的压缩动作 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 命令行调用
或者单个调用grunt htmlmin
更多信息