grunt的简单使用

来源:互联网 发布:js 菜单 展开收起 编辑:程序博客网 时间:2024/05/16 08:29

关于grunt的使用主要是两个文件的配置:

1.是gruntfile

2.是packagejson

首先是安装插件:

"connect-livereload": "^0.5.2",    "grunt-contrib-connect": "^0.9.0",    "grunt-contrib-watch": "^0.6.1",    "load-grunt-tasks": "^1.0.0",    "time-grunt": "^0.3.1",    "grunt-contrib-cssmin": "^2.1.0",    "grunt-contrib-htmlmin": "^2.3.0",    "grunt-usemin": "^3.1.1",
执行命令npm install xxx插件名 --save-dev安装到devdependece中

script中放入两个任务名一个dev和一个build

build执行的是压缩任务,dev执行运行调试


gruntfile中:

module.exports={}

中添加npm任务;

require('load-grunt-tasks')(grunt);
执行的是grunt.loadnpmtasks的任务

然后是其他任务配置:

 grunt.initConfig({  watch: {            //dev为定义监测任务的名字            dev: {                files: ['src/*.*'],                options: {                    livereload: 3030                }            }        },         //grunt-contrib-connect配置启动连接的Web服务器,是主要插件        connect: {            dev: {                options: {                    base: "src/html",                    //服务器端口                    port: 2222,                     // 服务器地址(可以使用主机名localhost,也能使用IP)                    hostname: '*',                    livereload: 3030,//页面自动刷新                     open: {                        target: 'http://127.0.0.2:2222'//target url to open, 目标路径                     }                }            }        },

 grunt.registerTask('dev', ['connect:dev', 'watch:dev']);

执行命令npm run dev将会执行pakage中的scripts的dev命令,然后执行grunt dev 然后执行connect和watch的dev任务

然后是build命令压缩html和css文件:

         //压缩CSS        cssmin:{            target:{                files:[{                    expand:true,                    cwd:'src/css',                    src:['*.css'],                    dest:'src_dest/css',                    //ext:'.min.css'                }]            }        },          //处理html中css、js 引入合并问题        usemin: {            html: 'src_dest/*.html'        },          //压缩HTML           htmlmin:{            options:{                removeComments: true,                removeCommentsFromCDATA: true,                collapseWhitespace: true,                collapseBooleanAttributes: true,                removeAttributeQuotes: true,                removeRedundantAttributes: true,                useShortDoctype: true,                removeEmptyAttributes: true,                removeOptionalTags: true                   },            html:{                files:[{                    expand: true,                     cwd: 'src/html',                     src: ['*.html'],                     dest: 'src_dest/html'                }]            }        }
cwd指定被压缩文件目录

dest是指定压缩的目标目录

sec指定压缩的文件

执行npm run build即可

这就是我简单的学习了