跨平台

Grunt了解

2020-03-17  本文已影响0人  平安喜乐698
目录
  1. 通过一个小练习来了解webpack

劝君莫惜金缕衣,劝君惜取少年时。 花开堪折直须折,莫待无花空折枝。
本文为本人略读官网文档后的大略笔记,实在不适合他人阅读

前言

JavaScript世界的自动化构建工具
对于需要反复重复的任务(例如压缩、编译、单元测试、linting等),自动化工具可以减轻工作

安装

# 全局安装
npm install -g grunt-cli

# 本地安装(项目)
npm install --save grunt

1. 通过一个小练习来了解webpack

第1步: 创建npm说明文件 package.json

npm init
填写 项目的名称、描述、作者等信息 ( 输入完成一项后回车输入下一项 )

注意:
  1. 项目名必须全小写
生成的package.json文件
{
  "name": "hello",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "cx",
  "license": "ISC",
}


注意:
  1. JSON文件不支持注释

第2步:本地安装grunt

npm install --save grunt
会自动修改package.json文件的dependencies字段内容

{
  "name": "hello",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "cx",
  "license": "ISC",
  "dependencies": {
    "grunt": "^1.1.0"
  }
}
这里再安装一个插件,用于转换less

npm install --save grunt-contrib-less

第3步:创建hello.less

body{
    width: 500px;
    height: 500px;
    @w:500px;
    @color:#FFF;
    div{
        width: @w;
        background-color: @color;
    }
}

第4步:创建Gruntfile.js(grunt的配置文件),并执行任务查看结果

module.exports = function(grunt) {
    // 初始化插件配置项
    grunt.initConfig({
        // 创建一个task
        less: {
            development: {
                // 会覆盖默认值
                options: {
                    // 压缩格式,不保留空格和缩进。生成的所有代码都在一行
                    compress: true 
                },
                // 没有build目录则自动创建
                // hello.less 转换成 result.css
                files: {
                    'build/result.css': 'test/hello.less'
                }
            },
            production: {
                options: {
                    paths: ["assets/css"], // @import 加载文件的路径
                    cleancss: true, // 压缩css文件
                    modifyVars: { // 重新定义全局变量
                        imgPath: '"http://mycdn.com/path/to/images"',
                        bgColor: 'blue'
                    }
                },
                files: {
                    'product/result.css': 'test/hello.less'
                }
            }
        }
    });
    // 启用/加载 grunt-contrib-less插件
    grunt.loadNpmTasks('grunt-contrib-less');

    // 注册上面的task。
    // default则在终端运行grupt即可执行转换任务。grunt.registerTask('hello', ['less']); 则在终端运行grupt hello。
    // 注意:这里执行的是development。
    grunt.registerTask('default', ['less']);
};

终端执行grunt

提示:(则成功)

Running "less:development" (less) task
>> 1 stylesheet created.

Done.

生成的result.css如下

body {
  width: 500px;
  height: 500px;
}
body div {
  width: 500px;
  background-color: #FFF;
}

执行production

方式1

// 注册任务,改成如下格式
grunt.registerTask('default', ['less:production']);

方式2

// 注册任务,改成如下格式
let target = grunt.option('target') || 'development';
grunt.registerTask('default', ['less:' + target]);

// development
grunt
// production
grunt default --target=production
上一篇 下一篇

猜你喜欢

热点阅读