zoukankan      html  css  js  c++  java
  • 前端自动化工具 -- Grunt 使用简介

    grunt是什么,grunt就是个东西..

    grunt作为一个前端构建工具,有资源压缩,代码检查,文件合并等功能。

    下面就简单了解grunt的使用。

    一、环境配置

    grunt是基于nodejs的,所以需要一个 nodejs 环境,未了解的可以 来这看看

    还是在windows下,

    首先要保证grunt命令可以使用,所以要先使用npm安装对应CLI

    npm install -g grunt-cli

    安装完成可以命令行中输入“grunt”测试是否安装成功

    安装成功后

    二、用法说明

    grunt需要package.json文件描述,很多操作都直接通过这个json文件访问,

            需要Gruntfile.js文件,这是一个入口文件,grunt将从这里开始,实现你的意图。

    所以,首先新建一个工程目录grunt,再里头新建这两个文件。

    package.json需要严格的json格式,随便写入几个key-value如:

    {
      "name": "grunt_test",
      "version": "1.0.0"
    }

    Gruntfile.js 可以初始成这个形式:

    module.exports = function(grunt){ 
        grunt.initConfig({ 
            pkg: grunt.file.readJSON('package.json')
            
        });
        //grunt.registerTask('default',[]);
    };

    这时我们命令行到工程目录里头,npm安装好grunt支持,后面的参数--dev-save表示将此grunt支持添加到依赖中去

    什么叫添加到依赖中去?安装好后,看看 package.json里头,是不是多了这个东西~

    {
      "name": "grunt_test",
      "version": "1.0.0",
      "devDependencies": {
        "grunt": "^0.4.5"
      }
    }

    好这时,我们用grunt命令执行一下,果然出现了没有default这货,看了它是需要这货的,那就把上头那个注释去掉,再试试

    其实到这里为止已经是最基本的流程了。

    三、各插件使用

    而一般常用方法是使用提供的 插件,进一步作处理

    1)比如代码压缩:

    html压缩:htmlmin

    css压缩: cssmin

    js压缩:uglify

    官方提供了充足的介绍,当然了,初次接触,也很容易被各种繁杂的配置项搞混。

    既然要压缩代码,这里就在./static/script/目录下新建一个test.js文件,随便写入几句

    function firstLetterToUp(str){ 
        return String(str).replace('^s*|s*$')
                    .replace(/w+/g,function(word){ 
                        word = word.toLowerCase();
                        return word[0].toUpperCase() + word.substring(1);
                    });
    }
    
    var s = firstLetterToUp('  aBCDE Bda erew');
    console.log(s);

    js代码压缩需要一个很常用的插件  grunt-contrib-uglify ,同理先npm安装支持

    可以看到package.json也更新了

    {
      "name": "grunt_test",
      "version": "1.0.0",
      "devDependencies": {
        "grunt": "^0.4.5",
        "grunt-contrib-uglify": "^0.9.1"
      }
    }

    类似的方法,html的安装 grunt-contrib-htmlmin ,css的安装 grunt-contrib-cssmin

    安装完后,接下来就是对Gruntfile.js更新配置项

    grunt.initConfig:定义各种模块的参数,每一个成员项对应一个同名模块。
    grunt.loadNpmTasks:加载完成任务所需的模块。
    grunt.registerTask:定义具体的任务。第一个参数为任务名,第二个参数是一个数组, 表示该任务需要依次使用的模块。

    各设置项都有一般用法,特殊的需要自行到官网查看说明,例如

    • expand:如果设为true,就表示下面文件名的占位符(即*号)都要扩展成具体的文件名。
    • cwd:需要处理的文件(input)所在的目录。
    • src:表示需要处理的文件。如果采用数组形式,数组的每一项就是一个文件名,可以使用通配符。
    • dest:表示处理后的文件名或所在目录。
    • ext:表示处理后的文件后缀名。

    目前的Gruntfile.js配置:

    module.exports = function(grunt){ 
        grunt.initConfig({ 
            //获取到package.json各项
            pkg: grunt.file.readJSON('package.json'),
            //js压缩
            uglify: { 
                //使用options这个名声
                options: { 
                    //为true表示允许添加头部信息
                    stripBanners: true,
                    //在头部添加 js文件名和时间的注释
                    banner: '/*! <%=pkg.name%>-<%=pkg.version%>.js <%=grunt.template.today("yyyy-mm-dd") %> */
    '
                },
                //files名称任意,比如下方的build 关键是src-dest要指示好
                files: { 
                    src: './static/script/test.js',
                    dest: 'build/static/script/<%=pkg.name%>-<%=pkg.version%>.min.js'
                }
            },
            //css 压缩
            cssmin: { 
                options:{ 
                    report:'gzip'
                },
                build: { 
                    expand: true,
                    cwd: './static/style',
                    src: ['test.css'],
                    dest: './build/static/style'
                }
            },
            //html 压缩
            htmlmin: { 
                options: { 
                removeComments: true,
                removeCommentsFromCDATA: true,
                collapseWhitespace: true,
                collapseBooleanAttributes: true,
                removeAttributeQuotes: true,
                removeRedundantAttributes: true,
                useShortDoctype: true,
                removeEmptyAttributes: true,
                removeOptionalTags: true
                },
                build:{ 
                    expand: true,
                    cwd: './',
                    src: ['*.html'],
                    dest: './'
                }
            }
        });
        
    
        grunt.loadNpmTasks('grunt-contrib-uglify');
        grunt.loadNpmTasks('grunt-contrib-cssmin');
        grunt.loadNpmTasks('grunt-contrib-htmlmin');
        
        grunt.registerTask('default',[
            'uglify',
            'cssmin',
            'htmlmin'
            ]);
    };

    命令行执行看效果

    当然了,还有图片的压缩 imagemin  也可以去试试

    2)jshint 代码检查

    js代码的检查可以使用 jshint插件

    同理,先 装好 grunt-contrib-jshint

    检查的规则见 DOCS

    curly: 大括号包裹

    eqeqeq: 对于简单类型,使用===和!==,而不是==和!=

    newcap: 对于首字母大写的函数(声明的类),强制使用new

    noarg: 禁用arguments.caller和arguments.callee

    sub: 对于属性使用aaa.bbb而不是aaa['bbb']

    undef: 查找所有未定义变量

    boss: 查找类似与if(a = 0)这样的代码

    node: 指定运行环境为node.js

    在Gruntfile.js中配置相关项:

    module.exports = function(grunt){ 
        grunt.initConfig({ 
            //获取到package.json各项
            pkg: grunt.file.readJSON('package.json'),
            //js压缩
            //... 省略
            },
            jshint: { 
                options: {
                    curly: true,
                    eqeqeq: true,
                    newcap: true,
                    noarg: true,
                    sub: true,
                    undef: true,
                    boss: true,
                    node: true,
                    globals: {
                        exports: true,
                        jQuery: true
                    }
                },
                files:['./static/script/test.js']
            }
        });
        grunt.loadNpmTasks('grunt-contrib-uglify');
        grunt.loadNpmTasks('grunt-contrib-cssmin');
        grunt.loadNpmTasks('grunt-contrib-htmlmin');
        grunt.loadNpmTasks('grunt-contrib-jshint');
    
        grunt.registerTask('default',[
            'jshint',
            'uglify',
            'cssmin',
            'htmlmin'
            ]);
    };                

    修改个,再执行grunt,可以看到出错信息,且grunt不再继续执行

    同理,csslint 也可作css的语法检查,可以去试试

    3)使用 grunt-contrib-watch 插件

    watch的使用会自动监听修改,并grunt自动构建

    同理,config中增添watch配置项

    files表示要监听的文件,可以是单个值或数组;tasks表示监听有改动后要执行什么任务

    watch: { 
                build: { 
                    files: ['./static/style/*.css'],
                    tasks: ['cssmin'],
                    options:{ 
                        spawn: false
                    }
                }
            }

    4)使用 grunt-contrib-sass 插件

    这个插件可以自动将sass编译成css文件,再配合其他插件的使用。美哉~

    装好支持依赖后,在config配置中增加:

    sass:{ 
                dist:{ 
                    options:{ 
                        //还记得这个不?这就是sass编译时候四种style中的
                        style: 'expanded'
                    },
                    files:{ 
                        './static/style/test.css':'./static/style/test.scss'
                    }
                }
            }

    files中就定义为  dest : src 的形式

    通过watch的辅助,执行命令后,scss文件的每次改动,都能自动构建出新css

     

    5)concat插件 文件合并 

    可以使用类似这种方式实现

    grunt.initConfig({
      concat: {
        options: {
          separator: ';',
        },
        dist: {
          src: ['src/intro.js', 'src/project.js', 'src/outro.js'],
          dest: 'dist/built.js',
        },
      },
    });

    当然还有很多插件经常被使用,比如clean copy 等等。这些都可以在grunt的 插件中心 找到,带contrib字样的表示是官方提供的。

    插件具体的用法,多种多样,还是自个去相应站点,好好读一读

    其实grunt这构建工具使用起来很简单,主要就是配置+一大堆配置。初期可能会对各配置项头痛,但经常实践,终会了然于胸的。

  • 相关阅读:
    jquery 序列化form表单
    nginx for windows 安装
    nodejs idea 创建项目 (一)
    spring 配置 shiro rememberMe
    idea 2018 解决 双击shift 弹出 search everywhere 搜索框的方法
    redis 在windows 集群
    spring IOC控制反转和DI依赖注入
    redis 的安装
    shiro 通过jdbc连接数据库
    handlebars的用法
  • 原文地址:https://www.cnblogs.com/imwtr/p/4668186.html
Copyright © 2011-2022 走看看