grunt 入门_Grunt入门简单指南

grunt 入门

Grunt is a task runner. This means that those repetitive tasks we deal with in our daily workflow gets Grunt是一个任务赛跑者。 这意味着我们在日常工作流程中处理的那些重复性任务将 automated. This will be a 实现自动化 。 这将是有关如何使用Grunt入门和运行的 simple look at how to get up and running with Grunt. We will look at doing the basic tasks: 简单介绍。 我们将看一下执行的基本任务:
  • Linting our JS files

    整理我们的JS文件
  • Minifying JS files

    缩小JS文件
  • Compiling LESS files

    编译LESS文件
  • Minifying CSS files

    缩小CSS文件
  • Watching our files for changes and doing the above tasks

    观看我们的文件进行更改并执行上述任务

A Quick Look at Grunt in Action

Let's say you wanted to check for errors in your JavaScript file. After you have setup Grunt, just run
$ grunt jshint
and you will see the errors in your JavaScript files! It's that easy to use Grunt. Just set it up and then call the task you want. Grunt will run the task for you. That's probably the official Grunt site calls it a taskrunner.

Making This Super Simple

There are many tutorials out there that talk about the great things you can do with Grunt. While great, sometimes they come with confusing and fully fledged configurations that are hard to understand for someone just getting into Grunt. This will be a guide in the basics of using Grunt and creating an incredibly simple and easy setup to handle the tasks mentioned above. This setup will teach us the basics but will let us think how we can expand Grunt for future more advanced uses.

快速查看行动中的咕unt声

假设您要检查JavaScript文件中的错误。 设置Grunt后,只需运行
$ grunt jshint
您将在JavaScript文件中看到错误! 使用Grunt非常简单。 只需进行设置,然后调用所需的任务即可。 Grunt将为您 运行任务。 这可能是Grunt官方网站将其称为 taskrunner

使这个超级简单

那里有许多教程介绍了使用Grunt可以做的很棒的事情。 虽然很棒,但有时它们带有令人困惑且功能齐全的配置,对于刚进入Grunt的人来说很难理解。 这将是 使用Grunt以及创建难以置信的简单易用的设置来处理上述任务 的基础指南 。 此设置将教我们一些基础知识,但会让我们思考如何扩展Grunt以便将来用于更高级的用途。

入门 ( Getting Started )

要使用Grunt,我们需要安装 Node.js installed. Don't worry, you can use Grunt in any application you want, whether it is a Node app, a PHP app, Wordpress, or just a plain old HTML/CSS/JS site. Node and its package manager (npm) are used to pull in the packages we need. Each package will have a different function like minifying or linting. If you don't already have Node installed on your computer, go ahead and Node.js。 不用担心,您可以在所需的任何应用程序中使用Grunt,无论它是Node应用程序,PHP应用程序,Wordpress还是只是普通的旧HTML / CSS / JS网站。 Node及其包管理器(npm)用于提取我们需要的包。 每个包装将具有不同的功能,例如缩小或掉毛。 如果你还没有在您的计算机上安装节点,继续前进, grab it and we'll start working with Grunt. To make sure that you have Node and npm installed, go into your command line and type 抓住它 ,我们将开始与步兵的工作。 要确保已安装Node和npm,请进入命令行并输入 node -v and node -vnpm -v. If you see version numbers, then you're ready to go! npm -v 。 如果看到版本号,就可以开始了!

Overview

We'll keep our project files very simple. This will be the file structure for our samples. Go ahead and create the folders and files shown. We'll leave our files blank and start adding to them later.
- dist              // will hold all our of final files (minified files)
----- css
----- js
- src               // will hold all of our original files
----- css
---------- style.css
---------- pretty.less
----- js
---------- magic.js
Gruntfile.js        // our Grunt configuration
package.json        // our npm pacakge configuration (how we pull in packages)
Notice how we have a src folder and a dist folder. We will be doing our work inside the src folder and Grunt will minify those files and save them into the dist folders. The files in dist are the ones that we will use for our final site.

Getting The Grunt Packages We Need

When using npm, we define the packages we need in a package.json file. Let's go into that file and add the packages we need. We'll explain what each package does also. name of our project, the version, and the devDependencies. This may seem weird at first for someone that hasn't used Node or npm before, but you'll see how npm is a very cool package manager for our project very soon.

Grunt Packages

You may be wondering what all of the grunt-contrib-**** packages do. Here's a handy table of the popular pacakages.
Plugin Description
contrib-jshint Validate files using jshint
contrib-uglify Minify JS files using UglifyJS
contrib-watch Run tasks whenever watched files are changed
contrib-clean Clean up files and folders
contrib-copy Copy files and folders
contrib-concat Combine files into a single file
contrib-cssmin Compress CSS files
contrib-less Compile LESS files to CSS
contrib-imagemin Minify PNG, JPG, and GIFs
contrib-compass Compile SASS to CSS using Compass
contrib-htmlmin Minify HTML files
For the full list of packages, visit the Grunt plugin repository. Now that we have the packages we need defined, let's install them.

Installing The Packages

With our package.json file ready to go, go into your command line and type:
$ npm install
You will see npm do its thing and pull those packages into a newly created node_modules folder. Now we have these packages and are ready to use them in our project. Now that our setup is all ready to go, let's set up our tasks for Grunt to do!

总览

我们将使我们的项目文件非常简单。 这将是我们样本的文件结构。 继续创建显示的文件夹和文件。 我们将文件保留为空白,稍后再开始添加。 src文件夹和 dist文件夹。 我们将在 src文件夹中进行工作,Grunt将缩小这些文件并将其保存到 dist文件夹中。 dist中的文件是我们将用于最终站点的文件。

获得我们需要的咕unt包

使用npm时,我们在 package.json文件中定义所需的软件包。 让我们进入该文件并添加所需的包。 我们将解释每个软件包的功能。
// package.json

{
  "name": "grunt-getting-started",
  "version": "0.1.0",
  "devDependencies": {
    "grunt": "~0.4.4",
    "grunt-contrib-jshint": "latest",
    "jshint-stylish": "latest",
    "grunt-contrib-uglify": "latest",
    "grunt-contrib-less": "latest",
    "grunt-contrib-cssmin": "latest",
    "grunt-contrib-watch": "latest"
  }
}
在这里,我们定义了项目的 nameversiondevDependencies 。 对于以前从未使用过Node或npm的人来说,这乍一看似乎很奇怪,但是您很快就会发现npm对于我们的项目来说是一个非常酷的软件包管理器。

咕unt包

您可能想知道所有 grunt-contrib-****软件包 grunt-contrib-**** 。 这是受欢迎的行动的方便餐桌。
插入 描述
贡献者 使用jshint验证文件
贡献 使用UglifyJS缩小JS文件
贡献表 更改观看文件时运行任务
清洁的 清理文件和文件夹
抄本 复制文件和文件夹
贡献者 将文件合并为一个文件
贡献者 压缩CSS文件
无贡献的 将LESS文件编译为CSS
贡献图像 缩小PNG,JPG和GIF
贡献罗盘 使用Compass将SASS编译为CSS
contrib-htmlmin 缩小HTML文件
有关软件包的完整列表,请访问 Grunt插件存储库 。 现在我们有了需要定义的软件包,让我们安装它们。

安装软件包

准备好我们的 package.json文件后,进入命令行并输入: node_modules文件夹中。 现在我们有了这些软件包,并准备在我们的项目中使用它们。 现在我们的设置已经准备就绪,让我们为Grunt设置任务吧!

Grunt设置和配置 ( Grunt Setup and Configuration )

为了定义Grunt的配置,我们将使用 Gruntfile.js file. This is the default place where our settings will go. Gruntfile.js文件。 这是我们设置的默认位置。

基础Gruntfile ( The Base Gruntfile )

在我们的 Gruntfile.js, let's go ahead and add in the basic things we need for our project. Gruntfile.js ,让我们继续添加项目所需的基本内容。
// Gruntfile.js

// our wrapper function (required by grunt and its plugins)
// all configuration goes inside this function
module.exports = function(grunt) {

  // ===========================================================================
  // CONFIGURE GRUNT ===========================================================
  // ===========================================================================
  grunt.initConfig({

    // get the configuration info from package.json ----------------------------
    // this way we can use things like name and version (pkg.name)
    pkg: grunt.file.readJSON('package.json'),

    // all of our configuration will go here

  });

  // ===========================================================================
  // LOAD GRUNT PLUGINS ========================================================
  // ===========================================================================
  // we can only load these if they are in our package.json
  // make sure you have run npm install so our app can find these
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-less');
  grunt.loadNpmTasks('grunt-contrib-cssmin');
  grunt.loadNpmTasks('grunt-contrib-watch');

};
We will use the module.exports (wrapper) function. This is the Node way of exposing our configuration to the rest of our application. We don't have to worry about this too much, but if you are interested, read this module.exports (包装器)功能。 这是将配置暴露给应用程序其余部分的Node方法。 我们不必为此担心太多,但是如果您有兴趣,请阅读有关该主题的 great article on the topic. Inside of our 出色文章 。 在 grunt.initConfig(), we have taken the information from our grunt.initConfig()内部,我们从 package.json and saved it to package.json获取了信息并将其保存到 pkg. With this, we can use the attributes from our package.json file. We can call the name of our project using pkg 。 这样,我们可以使用package.json文件中的属性。 我们可以把我们的使用项目的名称 pkg.name and the version with pkg.name并与版本 pkg.version. We could also expand this and even use an author. pkg.version 。 我们也可以扩展它,甚至可以使用作者。 Why do we need this? Good question. We'll see the usage in a bit, but one of the cool things we can do is use these attributes to create comments at the top of our files with project name, author, date built, and version! Pretty neat. We have also loaded our grunt plugins using 我们为什么需要这个? 好问题。 我们将稍等一下用法,但是我们可以做的很酷的事情之一就是使用这些属性在文件顶部创建注释,包括项目名称,作者,创建日期和版本! 漂亮整齐。 我们还使用 grunt.loadNpmTasks(). This is the way we can use the plugins that we brought in earlier using grunt.loadNpmTasks()加载了grunt插件。 这是我们可以使用之前使用 npm. npm引入的插件的方式。

套餐配置 ( Package Configuration )

准备好基本的Grunt配置后,让我们来看一下配置其中一个软件包的方法。 让我们从JSHint包开始,以整理我们JavaScript文件并告诉我们是否有任何错误。 这是Grunt知道我们希望它整理,缩小或要做其他任何事情的文件的方式。 当我们配置软件包时,它将进入我们的 grunt.initConfig() section and it will follow a certain structure. Here is the basic structure of configuring a Grunt package: grunt.initConfig()部分,它将遵循某种结构。 这是配置Grunt软件包的基本结构:
// Gruntfile.js

grunt.initConfig({

    // configure jshint to validate js files -----------------------------------
    jshint: {
      options: {
        reporter: require('jshint-stylish') // use jshint-stylish to make our errors look and read good
      },

      // when this task is run, lint the Gruntfile and all js files in src
      build: ['Gruntfile.js', 'src/**/*.js']
    }

});
This will be the basic format for how we configure our packages. We will:
  1. Call the name of the package (jshint)

    调用包的名称( jshint
  2. Set options if we have to. These are usually found on the docs for each specific package

    如果需要,请设置选项。 这些通常可以在每个特定软件包的文档中找到
  3. Create a build attribute and pass in files, directories, or anything else we want.

    创建一个build属性,并传入文件,目录或我们想要的其他任何内容。

命名约定 ( Naming Conventions )

在命名任务时,我们将命名主任务 build. You can name this what you want and you could even create more than one task. When you run grunt, all of the tasks will automatically be run. If you wanted to create tasks within the build 。 您可以根据自己的需要命名,甚至可以创建多个任务。 当您运行grunt时,所有任务将自动运行。 如果要在 jshint configuration, you could name them jshint配置中创建任务,可以将其命名为 dev and devproduction. Then we can call the tasks later by using production 。 然后,我们可以稍后使用 jshint:dev or jshint:devjshint:production. Now that we have seen the basic setup for a Grunt package, let's go ahead and start creating configurations for the tasks we want to do. jshint:production调用任务。 既然我们已经了解了Grunt软件包的基本设置,那么我们就开始为想要执行的任务创建配置。

整理JavaScript文件 ( Linting JavaScript Files )

这是插入JavaScript文件的配置。 与上面的示例相同。 我们还引入了 'jshint-stylish' package to make our error output look good. 'jshint-stylish'包,以使我们的错误输出看起来不错。
// Gruntfile.js

grunt.initConfig({

    ...

    // configure jshint to validate js files -----------------------------------
    jshint: {
      options: {
        reporter: require('jshint-stylish') // use jshint-stylish to make our errors look and read good
      },

      // when this task is run, lint the Gruntfile and all js files in src
      build: ['Grunfile.js', 'src/**/*.js']
    }

});
Go ahead and add in some JS into src/js/magic.js src/js/magic.js添加一些JS
// src/js/magic.js

var hello = 'look im grunting!'

var awesome = 'yes it is awesome!'
Now if we run:
$ grunt jshint
in our command line, we'll see it lint the Gruntfile and all JS files inside the src folder. src文件夹中的所有JS文件变得不整齐。
grunt-jshint-errors
** for all folders and **对所有文件使用 * for all files. With linting out of the way, let's look at minifying. * 。 在不掉毛的情况下,让我们来看一下最小化。

Minifying JavaScript Files

We'll follow the same format. We will call the uglify package, configure it, and tell it what files to use and create.
// Gruntfile.js
grunt.initConfig({

    // get the configuration info from package.json ----------------------------
    // this way we can use things like name and version (pkg.name)
    pkg: grunt.file.readJSON('package.json'),

    ...

    // configure uglify to minify js files -------------------------------------
    uglify: {
      options: {
        banner: '/*\n <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> \n*/\n'
      },
      build: {
        files: {
          'dist/js/magic.min.js': 'src/js/magic.js'
        }
      }
    }

});
Here we are configuring an option called banner. This will add a nice comment to the top of our minified file. Notice we are using the pkg.name from the package.json file. In our build, we are defining the file we want to create ( dist/js/magic.min.js) from the src file ( src/js/magic.js). We will want more code in our file than just those two lines we made so let's go grab a giant file to minify. Let's go get jQuery. Copy everything from the unminified jQuery file and paste it into our src/js/magic.js file. See how they have their cool comment at the top of the file? We can build one of those out using the banner option. With our file, let's go ahead and minify it. Go into your console and type: Now we have taken our file from the original 360kb to a nice sized 97.1kb!

Minifying Multiple Files into One

We can also do much more than just minify a single file. We can take multiple files and minify them to one output file. This can speed up our sites since we are only serving one JS file to the users visiting our site. To configure multiple files is straightforward: magic.min.js. We can also use the shortcut we learned earlier and just say all js files in the src folder should be minified. You would use ( src/**/*.js) for that.

缩小JavaScript文件

我们将遵循相同的格式。 我们将调用 uglify软件包,对其进行配置,并告诉它要使用和创建的文件。
// Gruntfile.js
grunt.initConfig({

    // get the configuration info from package.json ----------------------------
    // this way we can use things like name and version (pkg.name)
    pkg: grunt.file.readJSON('package.json'),

    ...

    // configure uglify to minify js files -------------------------------------
    uglify: {
      options: {
        banner: '/*\n <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> \n*/\n'
      },
      build: {
        files: {
          'dist/js/magic.min.js': 'src/js/magic.js'
        }
      }
    }

});
在这里,我们配置了一个名为 banner的选项。 这将在我们的缩小文件的顶部添加一个很好的注释。 注意,我们正在使用package.json文件中的 pkg.name 。 在我们的 build ,我们定义了要从src文件( src/js/magic.js )创建的文件( dist/js/magic.min.js src/js/magic.js )。 除了文件中的两行代码外,我们还需要更多的代码,所以让我们抓取一个巨大的文件来缩小代码。 我们去获取jQuery。 复制未 缩小的jQuery文件中的所有内容并将其粘贴到我们的 src/js/magic.js文件中。 看看他们在文件顶部有什么很酷的评论吗? 我们可以使用banner选项构建其中之一。 使用我们的文件,让我们继续进行最小化。 进入控制台并输入: 现在,我们已经将文件从原始的360kb扩展到了97.1kb!

将多个文件压缩到一个

除了缩小单个文件,我们还可以做更多的事情。 我们可以提取多个文件,并将它们最小化为一个输出文件。 由于我们仅向访问我们网站的用户提供一个JS文件,因此可以加快我们的网站的速度。 配置多个文件很简单: magic.min.jsmagic.min.js 。 我们还可以使用我们之前学习的快捷方式,只是说应该缩小 src文件夹中的所有js文件。 您可以使用( src/**/*.js )。

将LESS编译为CSS ( Compiling LESS to CSS )

尽管在本示例中将使用LESS,但是您也可以使用 grunt-contrib-compass package to do the same for SASS. Here's our configuration for compiling LESS files. Like our minifying JS example, we will use our config to define the source and output files. grunt-contrib-compass软件包对SASS进行相同的操作。 这是我们用于编译LESS文件的配置。 就像我们的JS缩小示例一样,我们将使用配置来定义源文件和输出文件。
// Gruntfile.js
grunt.initConfig({

    ...

    // compile less stylesheets to css -----------------------------------------
    less: {
      build: {
        files: {
          'dist/css/pretty.css': 'src/css/pretty.less'
        }
      }
    }

});
For this example, we aren't going to be setting any options. Just compile our src/css/pretty.less to a src/css/pretty.less编译为 dist/css/pretty.css file. Let's add in some LESS into our source file. dist/css/pretty.css文件即可。 让我们在源文件中添加一些LESS。
/* src/css/pretty.less */

@red        : #CC594A;
@yellow     : #B8CC24;
@blue       : #8BC5FF;
@purple     : #6F3596;

body        { 
    background:@red;
    color:@yellow;
}

button      {
    background:@blue;
}

div         {
    background:@purple;
}
Now we have defined some LESS variables and applied them to our elements. Let's go ahead and run our task!
$ grunt less
grunt-less-compile
dist/css/pretty.css file all of our LESS compiled to CSS and that file now looks like a normal stylesheet. dist/css/pretty.css文件,并将其编译为CSS,现在该文件看起来像一个普通的样式表。
/* dist/css/pretty.css */

body {
  background: #cc594a;
  color: #b8cc24;
}
button {
  background: #8bc5ff;
}
div {
  background: #6f3596;
}
Let's look at two more things we can do with Grunt.

缩小CSS文件 ( Minifying CSS Files )

就像缩小JS文件一样,此配置将非常简单。 现在,我们开始进行练习,让我们继续创建此配置。
// Gruntfile.js
grunt.initConfig({

    ...

    // configure cssmin to minify css files ------------------------------------
    cssmin: {
      options: {
        banner: '/*\n <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> \n*/\n'
      },
      build: {
        files: {
          'dist/css/style.min.css': 'src/css/style.css'
        }
      }
    }

});
Now if you run:
$ grunt cssmin
We will have our newly minified dist/css/style.min.css file. dist/css/style.min.css文件。

一次运行多个任务 ( Running Multiple Tasks at Once )

现在,我们了解了所有任务的工作方式,让我们提高效率并仅通过一项任务即可运行所有任务。 这比运行单独的呼叫更好的 grunt uglify, grunt uglifygrunt jshint, and so on. grunt jshint ,等等。

默认任务 ( Default Task )

使用Grunt,您可以创建将同时运行多个任务的任务。 例如,假设我们只想通过调用 grunt. When you run grunt完成上述所有任务。 当您从命令行运行 grunt from the command line, Grunt will look for a task called grunt ,Grunt将查找名为 default. Let's create that now so we can see what it looks like. default的任务。 现在创建它,以便我们可以看到它的外观。
// Gruntfile.js

grunt.initConfig({

  ...

  // ============= // CREATE TASKS ========== //
  grunt.registerTask('default', ['jshint', 'uglify', 'cssmin', 'less']); 

});
Now just run:
$ grunt
and all of the tasks in our default task will run! Now let's look at how we can register different tasks for different environments. default任务中的所有任务都将运行! 现在让我们看看如何为不同的环境注册不同的任务。

针对不同环境的不同任务 ( Different Tasks for Different Environments )

假设我们想让Grunt在开发环境中为我们工作,然后在我们进行生产时,我们希望运行不同的任务。 我们可以在每个配置中定义多个任务。 例如:
// Gruntfile.js

grunt.initConfig({

  // get the configuration info from package.json ---------------------------- 
  // this way we can use things like name and version (pkg.name) 
  pkg: grunt.file.readJSON('package.json'),

...

// configure uglify to minify js files ------------------------------------- 
  uglify: { 
    options: { 
      banner: '/\n <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> \n/\n' 
    }, 
    dev: { 
      files: { 'dist/js/magic.min.js': ['src/js/magic.js', 'src/js/magic2.js'] } 
    }, 
    production: { 
      files: { 'dist/js/magic.min.js': 'src/**/*.js' } 
    } 
  }
});
Now we can call them differently using a colon. Let's create a task for development and production.
// Gruntfile.js

grunt.initConfig({

  // ========= // CREATE TASKS =========

  // this default task will go through all configuration (dev and production) in each task 
  grunt.registerTask('default', ['jshint', 'uglify', 'cssmin', 'less']);

  // this task will only run the dev configuration 
  grunt.registerTask('dev', ['jshint:dev', 'uglify:dev', 'cssmin:dev', 'less:dev']);

  // only run production configuration 
  grunt.registerTask('production', ['jshint:production', 'uglify:production', 'cssmin:production', 'less:production']);

});
Now we can call development by running:
$ grunt dev
or production by running:
$ grunt production
Now we've seen how we can create multiple configurations for our tasks and call them differently. Let's look at the last thing we'll be creating today. We'll watch our files and have Grunt run every time a file changes!

观察变化并运行任务 ( Watching For Changes and Running Tasks )

监视任务将在每次更改和保存文件时运行。 我们要做的就是将其配置为监视某些文件,并告诉它们在更改这些文件时该怎么做。 我们将打破我们一直在使用的基本 build configuration we've been using. Here we'll separate it out into stylesheets and scripts. We do this because we want to use different tasks for each. build配置。 在这里,我们将其分为样式表和脚本。 我们这样做是因为我们要为每个任务使用不同的任务。
// Gruntfile.js

grunt.initConfig({

...

// configure watch to auto update ----------------
watch: {

  // for stylesheets, watch css and less files 
  // only run less and cssmin stylesheets: { 
  files: ['src//*.css', 'src//*.less'], 
  tasks: ['less', 'cssmin'] },

  // for scripts, run jshint and uglify 
  scripts: { 
    files: 'src/**/*.js', tasks: ['jshint', 'uglify'] 
  } 
}

});
Now we have configured watch to watch our stylesheets and scripts. In your console, run:
$ grunt watch
Now we can see that Grunt will watch for changes and run the tasks it needs to.
grunt-watch-example
minify images. 缩小图像

结论 ( Conclusion )

希望这种对Grunt的简化外观将开始产生一些关于如何将Grunt用于特定工作流的想法。 启动和运行就像 installing a package, 安装软件包configuring the package, and typing 配置软件包并键入 grunt! Definitely look through the official grunt一样容易! 一定要仔细阅读官方 docs and the 文档plugins list to get more ideas on how to use Grunt. 插件列表,以获取有关如何使用Grunt的更多想法。

翻译自: https://scotch.io/tutorials/a-simple-guide-to-getting-started-with-grunt

grunt 入门

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值