本文共 20222 字,大约阅读时间需要 67 分钟。
grunt 入门
$ grunt jshintand 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.
$ grunt jshint您将在JavaScript文件中看到错误! 使用Grunt非常简单。 只需进行设置,然后调用所需的任务即可。 Grunt将为您 运行任务。 这可能是Grunt官方网站将其称为 taskrunner 。
node -v
and node -v
和 npm -v
. If you see version numbers, then you're ready to go! npm -v
。 如果看到版本号,就可以开始了! - 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.jsGruntfile.js // our Grunt configurationpackage.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. 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-contrib-****
packages do. Here's a handy table of the popular pacakages. Plugin | Description |
---|---|
Validate files using jshint | |
Minify JS files using UglifyJS | |
Run tasks whenever watched files are changed | |
Clean up files and folders | |
Copy files and folders | |
Combine files into a single file | |
Compress CSS files | |
Compile LESS files to CSS | |
Minify PNG, JPG, and GIFs | |
Compile SASS to CSS using Compass | |
Minify HTML files |
package.json
file ready to go, go into your command line and type: $ npm installYou 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
中的文件是我们将用于最终站点的文件。 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" }}在这里,我们定义了项目的
name
, version
和 devDependencies
。 对于以前从未使用过Node或npm的人来说,这乍一看似乎很奇怪,但是您很快就会发现npm对于我们的项目来说是一个非常酷的软件包管理器。 grunt-contrib-****
软件包 grunt-contrib-****
。 这是受欢迎的行动的方便餐桌。 插入 | 描述 |
---|---|
使用jshint验证文件 | |
使用UglifyJS缩小JS文件 | |
更改观看文件时运行任务 | |
清理文件和文件夹 | |
复制文件和文件夹 | |
将文件合并为一个文件 | |
压缩CSS文件 | |
将LESS文件编译为CSS | |
缩小PNG,JPG和GIF | |
使用Compass将SASS编译为CSS | |
缩小HTML文件 |
package.json
文件后,进入命令行并输入: node_modules文件夹中。 现在我们有了这些软件包,并准备在我们的项目中使用它们。 现在我们的设置已经准备就绪,让我们为Grunt设置任务吧! Gruntfile.js
file. This is the default place where our settings will go. Gruntfile.js
文件。 这是我们设置的默认位置。 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 functionmodule.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方法。 我们不必为此担心太多,但是如果您有兴趣,请阅读有关该主题的 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引入的插件的方式。 grunt.initConfig()
section and it will follow a certain structure. Here is the basic structure of configuring a Grunt package: grunt.initConfig()
部分,它将遵循某种结构。 这是配置Grunt软件包的基本结构: // Gruntfile.jsgrunt.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:
jshint
) 调用包的名称( jshint
) build
attribute and pass in files, directories, or anything else we want. 创建一个build
属性,并传入文件,目录或我们想要的其他任何内容。 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 dev
和 production
. Then we can call the tasks later by using production
。 然后,我们可以稍后使用 jshint:dev
or jshint:dev
或 jshint: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软件包的基本设置,那么我们就开始为想要执行的任务创建配置。 'jshint-stylish'
package to make our error output look good. 'jshint-stylish'
包,以使我们的错误输出看起来不错。 // Gruntfile.jsgrunt.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.jsvar hello = 'look im grunting!'var awesome = 'yes it is awesome!'Now if we run:
$ grunt jshintin our command line, we'll see it lint the Gruntfile and all JS files inside the
src
folder. src
文件夹中的所有JS文件变得不整齐。 **
for all folders and **
对所有文件使用 *
for all files. With linting out of the way, let's look at minifying. *
。 在不掉毛的情况下,让我们来看一下最小化。 uglify
package, configure it, and tell it what files to use and create. // Gruntfile.jsgrunt.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 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: 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. uglify
软件包,对其进行配置,并告诉它要使用和创建的文件。 // Gruntfile.jsgrunt.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。 复制未 所有内容并将其粘贴到我们的 src/js/magic.js
文件中。 看看他们在文件顶部有什么很酷的评论吗? 我们可以使用banner选项构建其中之一。 使用我们的文件,让我们继续进行最小化。 进入控制台并输入: magic.min.js
到 magic.min.js
。 我们还可以使用我们之前学习的快捷方式,只是说应该缩小 src
文件夹中的所有js文件。 您可以使用( src/**/*.js
)。 // Gruntfile.jsgrunt.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
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.
// Gruntfile.jsgrunt.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 cssminWe will have our newly minified
dist/css/style.min.css
file. dist/css/style.min.css
文件。 grunt uglify
, grunt uglify
, grunt jshint
, and so on. grunt jshint
,等等。 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.jsgrunt.initConfig({ ... // ============= // CREATE TASKS ========== // grunt.registerTask('default', ['jshint', 'uglify', 'cssmin', 'less']); });Now just run:
$ gruntand 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
任务中的所有任务都将运行! 现在让我们看看如何为不同的环境注册不同的任务。 // Gruntfile.jsgrunt.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.jsgrunt.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 devor production by running:
$ grunt productionNow 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!
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.jsgrunt.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 watchNow we can see that Grunt will watch for changes and run the tasks it needs to.
翻译自:
grunt 入门
转载地址:http://yiywd.baihongyu.com/