javascript grunt安装和使用
grunt是javascript世界的构建工具。
为何要用构建工具?
一句话:自动化。对于需要反复重复的任务,例如压缩(minification)、编译、单元测试、linting等。自动化工具可以减轻你的劳动,简化你的工作。当你正确配置好了任务,任务运行器就会帮你自动完成大部分无聊的工作。
为什么要使用Grunt?
Grunt生态系统非常庞大,并且一直在增长。由于拥有数量庞大的插件可供选择,因此,你可以利用Grunt自动完成任何事,并且花费最少的代价。如果找不到你所需要的插件,那就自己动手创造一个Grunt插件,然后将其发布到npm上吧。
http://www.gruntjs.org/article/installing_grunt.html
通过npm安装:
Install grunt-cli globally with npm install -g grunt-cli.
http://www.cnblogs.com/snandy/archive/2013/03/11/2949177.html
官网教程:
http://gruntjs.com/getting-started
Installing the CLI
Using Grunt 0.3? Please see Grunt 0.3 Notes
In order to get started, you'll want to install Grunt's command line interface (CLI) globally. You may need to use sudo (for OSX, *nix, BSD etc) or run your command shell as Administrator (for Windows) to do this.
npm install -g grunt-cli
This will put the grunt command in your system path, allowing it to be run from any directory.
Note that installing grunt-cli does not install the Grunt task runner! The job of the Grunt CLI is simple: run the version of Grunt which has been installed next to a Gruntfile. This allows multiple versions of Grunt to be installed on the same machine simultaneously.
How the CLI works
Each time grunt is run, it looks for a locally installed Grunt using node's require() system. Because of this, you can run grunt from any subfolder in your project.
If a locally installed Grunt is found, the CLI loads the local installation of the Grunt library, applies the configuration from your Gruntfile, and executes any tasks you've requested for it to run. To really understand what is happening, read the code.
Working with an existing Grunt project
Assuming that the Grunt CLI has been installed and that the project has already been configured with apackage.json and a Gruntfile, it's very easy to start working with Grunt:
- Change to the project's root directory.
- Install project dependencies with
npm install. - Run Grunt with
grunt.
That's really all there is to it. Installed Grunt tasks can be listed by running grunt --help but it's usually a good idea to start with the project's documentation.
Preparing a new Grunt project
A typical setup will involve adding two files to your project: package.json and the Gruntfile.
package.json: This file is used by npm to store metadata for projects published as npm modules. You will list grunt and the Grunt plugins your project needs as devDependencies in this file.
Gruntfile: This file is named Gruntfile.js or Gruntfile.coffee and is used to configure or define tasks and load Grunt plugins. When this documentation mentions a Gruntfile it is talking about a file, which is either a Gruntfile.js or a Gruntfile.coffee.
package.json
The package.json file belongs in the root directory of your project, next to the Gruntfile, and should be committed with your project source. Running npm install in the same folder as a package.json file will install the correct version of each dependency listed therein.
There are a few ways to create a package.json file for your project:
- Most grunt-init templates will automatically create a project-specific
package.jsonfile. - The npm init command will create a basic
package.jsonfile. - Start with the example below, and expand as needed, following this specification.
{
"name": "my-project-name",
"version": "0.1.0",
"devDependencies": {
"grunt": "~0.4.5",
"grunt-contrib-jshint": "~0.10.0",
"grunt-contrib-nodeunit": "~0.4.1",
"grunt-contrib-uglify": "~0.5.0"
}
}
Installing Grunt and gruntplugins
The easiest way to add Grunt and gruntplugins to an existing package.json is with the commandnpm install <module> --save-dev. Not only will this install <module> locally, but it will automatically be added to the devDependencies section, using a tilde version range.
For example, this will install the latest version of Grunt in your project folder, adding it to your devDependencies:
npm install grunt --save-dev
The same can be done for gruntplugins and other node modules. Be sure to commit the updatedpackage.json file with your project when you're done!
The Gruntfile
The Gruntfile.js or Gruntfile.coffee file is a valid JavaScript or CoffeeScript file that belongs in the root directory of your project, next to the package.json file, and should be committed with your project source.
A Gruntfile is comprised of the following parts:
- The "wrapper" function
- Project and task configuration
- Loading Grunt plugins and tasks
- Custom tasks
An example Gruntfile
In the following Gruntfile, project metadata is imported into the Grunt config from the project'spackage.json file and the grunt-contrib-uglify plugin's uglify task is configured to minify a source file and generate a banner comment dynamically using that metadata. When grunt is run on the command line, theuglify task will be run by default.
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
build: {
src: 'src/<%= pkg.name %>.js',
dest: 'build/<%= pkg.name %>.min.js'
}
}
});
// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-uglify');
// Default task(s).
grunt.registerTask('default', ['uglify']);
};
更多看文档.
bootstrap编译css和javascript:
Bootstrap 使用 Grunt 作为编译系统,并且对外提供了一些方便的方法用于编译整个框架。下面讲解的就是如何编译源码、运行测试用例等内容。
安装 Grunt
安装 Grunt 前,你需要首先下载并安装 node.js (npm 已经包含在内)。npm 是 node packaged modules 的简称,它的作用是基于 node.js 管理扩展包之间的依赖关系。
然后在命令行中输入以下命令:
- 在全局环境中安装
grunt-cli:npm install -g grunt-cli。 - 进入
/bootstrap/根目录,然后执行npm install命令。npm 将读取package.json文件并自动安装此文件中列出的所有被依赖的扩展包。
上述步骤完成后,你就可以运行 Bootstrap 所提供的各个 Grunt 命令了。
创建任务
grunt.registerTask(taskName, [description,] taskFunction)
taskName 任务名称,命令行里使用 grunt + taskName
description 任务的描述
taskFunction 任务的实现
Gruntfile.js里填入一下代码
module.exports = function(grunt) {
grunt.registerTask('mytask', '一个最简单的任务演示,根据参数打印不同的输出.', function(arg1, arg2) {
if (arguments.length === ) {
grunt.log.writeln('任务' + this.name + ", 没有传参数");
} else if (arguments.length === ) {
grunt.log.writeln('任务' + this.name + ", 有一个参数是" + arg1);
} else {
grunt.log.writeln('任务' + this.name + ", 有两个参数分别是" + arg1 + ", " + arg2);
}
});
};
注册了一个任务“mytask”,实现一个最简单的根据所传参数不同实现不同的打印输出,看运行结果我们需要进入命令行。
进入到g1目录,输入 grunt mytask
再输入 grunt mytask:snandy
任务名后面加一个冒号就可以传参了
当然,定义任务的时候也可以指定参数(详见第二章)。比如下面这个例子:
然后在任务中你可以运行其他任务:
- grunt.registerTask('foo', 'My "foo" task.', function() {
- // Enqueue "bar" and "baz" tasks, to run after "foo" finishes, in-order.
- grunt.task.run('bar', 'baz');
- // Or:
- grunt.task.run(['bar', 'baz']);
- });
grunt-contrib-concat
非常常用的grunt插件,用于合并任意文件,用法也非常简单:
npm install grunt-contrib-concat --save-dev
grunt.loadNpmTasks('grunt-contrib-concat');
(后面的插件演示就不再贴安装插件和注册插件的代码,大同小异。)
任务:合并src下的js文件到build目录,合并后文件名为built.js。
grunt.initConfig({
concat: {
options: {
//文件内容的分隔符
separator: ';'
},
dist: {
src: ['src/*.js'],
dest: 'build/built.js'
}
}
});
向文件追加一些额外信息:
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
//文件内容的分隔符
separator: ';',
stripBanners: true,
banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %> */'
},
dist: {
}
}
});
自定义进程函数,比如你需要在合并文件前,对文件名进行处理等。
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
// Replace all 'use strict' statements in the code with a single one at the top
banner: "'use strict';\n",
process: function(src, filepath) {
return '// Source: ' + filepath + '\n' +
src.replace(/(^|\n)[ \t]*('use strict'|"use strict");?\s*/g, '$1');
}
},
dist: {
}
}
});
(后期配置:
dist = {src: concatSrc, dest: concatDest};
grunt.config('concat.dist', dist);
)
grunt-contrib-copy
顾名思义,用于复制文件或目录的插件。
copy: {
main: {
files: [
{src: ['path/*'], dest: 'dest/', filter: 'isFile'}, // 复制path目录下的所有文件
{src: ['path/**'], dest: 'dest/'}, // 复制path目录下的所有目录和文件
]
}
}
有复制,必然有删除。
grunt-contrib-clean
clean: {
build: {
src: ["path/to/dir/one", "path/to/dir/two"]
}
}
grunt-contrib-compress
用于压缩文件和目录成为zip包,不是很常用。
compress: {
main: {
options: {
archive: 'archive.zip'
},
files: [
{src: ['path/*'], dest: 'internal_folder/', filter: 'isFile'}, path下所有的js
{src: ['path/**'], dest: 'internal_folder2/'}, // path下的所有目录和文件
]
}
}
grunt-contrib-jshint
jshint用于javascript代码检查(并会给出建议),发布js代码前执行jshint任务,可以避免出现一些低级语法问题。
jshint拥有非常丰富的配置,可以自由控制检验的级别。
module.exports = function(grunt) {
// 构建任务配置
grunt.initConfig({
//读取package.json的内容,形成个json数据
pkg: grunt.file.readJSON('package.json'),
jshint: {
options: {
//大括号包裹
curly: true,
//对于简单类型,使用===和!==,而不是==和!=
eqeqeq: true,
//对于首字母大写的函数(声明的类),强制使用new
newcap: true,
//禁用arguments.caller和arguments.callee
noarg: true,
//对于属性使用aaa.bbb而不是aaa['bbb']
sub: true,
//查找所有未定义变量
undef: true,
//查找类似与if(a = 0)这样的代码
boss: true,
//指定运行环境为node.js
node: true
},
//具体任务配置
files: {
src: ['src/*.js']
}
}
});
// 加载指定插件任务
grunt.loadNpmTasks('grunt-contrib-jshint');
// 默认执行的任务
grunt.registerTask('default', ['jshint']);
};
http://ju.outofmemory.cn/entry/39815
javascript grunt安装和使用的更多相关文章
- Grunt安装配置教程:前端自动化工作流
Grunt这货是啥? Grunt 是一个基于任务的 JavaScript 项目命令行构建工具. 最近很火的前端自动化小工具,基于任务的命令行构建工具 http://gruntjs.com Grunt能 ...
- grunt安装
随着node的流行,各种后台的技术应用到前端,依赖注入.自动化测试.构建等等. 本篇就介绍下如何使用Grunt进行构建. grunt安装 由于grunt依赖于nodejs,因此需要先安装nodejs. ...
- Grunt安装中遇到的问题汇总
Grunt安装中遇到的问题汇总 1.如果是windows下的dos中安装Grunt,必须以管理员身份登录(第一个坑) 登录方法是: 方法一:开始>所有程序>附件>命令提示符上右键&g ...
- grunt安装与配置
安装 CLI npm install -g grunt-cli//全局安装 npm init //初始化package.json npm init 命令会创建一个基本的package.json文件 ...
- Grunt 安装与配置环境
当时学习 Grunt 的时候,真是很头疼.分了两个时间段,学习了两次才硬啃下来,之后才能用在项目中.主要原因我认为是学习资料和文档上面写的太高端了.这类的文档或者资料有个显著特点,上来先简单介绍一下这 ...
- grunt 安装使用(一)
grunt 依赖nodejs,所有在使用前确保你安装了nodejs,然后开始执行grunt命令. .安装node nodejs安装教程 安装完成后在命令行,执行命令: node -v 出现版本信息, ...
- grunt安装和使用教程
grunt的安装 npm intall -g grunt-cli 新建文件夹grunt,在本地文件中添加package.json和Gruntfile.js文件,其中package.json文件的配置如 ...
- grunt安装与运行
用grunt前,需要先安装nodejs.因为grunt依赖于nodejs.nodejs的安装可以参照我的博客里头的nodejs的下载,安装与测试. 第一步:安装grunt-CLI 注意你的电脑要联 ...
- grunt安装、配置、在webstrom中使用
1.全局范围安装 Grunt命令行(CLI) npm install -g grunt-cli Grunt CLI的任务很简单:调用与Gruntfile在同一目录中 Grunt.这样带来的好处是,允许 ...
随机推荐
- MinGW-64 安装
一.在mingw-w64官网下载mingw-w64在线安装包 二.点击mingw-w64进行安装,选择: Version:选最新版本 我这个是4.9.2 Architecture:x86_64 (64 ...
- Kill 所有MySQL进程
如果在单机上安装了N多mysql数据库单实例,不再使用的情况下,想关闭所有进程,方法很简单的了,哈哈哈. kill -9 `ps -ef|grep DataServer|awk '{print $2} ...
- RDD的转换操作---RDD转换过程
1) union(otherRDD)RDD-->UnionRDD2) groupByKey(numPartitions)RDD-->ShuffledRDD-->MapPartitio ...
- user-agent中的mozilla
ie说我等不急了,所以user-agent增加 mozilla标识 这篇文章极其好玩:http://nonfu.me/p/8262.html
- wampserver修改mysql数据库密码后phpMyAdmin无法连接数据库
phpMyAdmin开始能打开,但是我在权限里把root的密码改了,再打开phpMyAdmin就显示:“phpMyAdmin 试图连接到 MySQL 服务器,但服务器拒绝连接.您应该检查 config ...
- centos 64位linux系统下安装appt命令
首先,安装apktool包 1. wget http://android-apktool.googlecode.com/files/apktool-install-linux-r04-brut1.ta ...
- ListView防止滑动变色的小技巧
listview滑动时会变成白色,如果背景色不是白色的话可以通过设置setCacheColorHint(Color.TRANSPARENT);来避免变色,.对应的xml也可以进行设置.
- 在云服务器搭建WordPress博客(二)使用xampp并解决端口冲突问题
要搭建一台外界可以访问的服务器,就必须有对应的服务器环境.在这里我用的xampp集成环境(我是菜鸟级......),xampp集成了PHP+Apache+MySQL+perl,安装方便,不用再特意去设 ...
- Fixing:insert_modules not found
搞linux的最怕的就是panic.满屏的报错不知头绪,百度出来的还都是抄来抄去的垃圾. 我遇到的错误已经解决,所以不想再看到报错了..google出来两个没有上下文的文本,因为和他们差不多,在下面贴 ...
- hadoop 技巧
通过--config指定不同的集群 bin/hadoop --config ./conf_time/ dfs -ls /user/rd/*/for_*/ip_table/output/ rd下是都读写 ...