RequireJs 提供了一个打包工具 r.js,能够将相关的模块打包为一个文件。相关说明:http://www.requirejs.org/docs/optimization.htmlhtml
虽然能够经过命令行来使用这个打包工具,可是在 Grunt 中也提供了相应的插件来自动完成这个任务。java
地址:https://github.com/gruntjs/grunt-contrib-requirejs node
npm install grunt-contrib-requirejs --save-dev
控制台输出jquery
grunt-contrib-requirejs@0.4.4 node_modules\grunt-contrib-requirejs
└── requirejs@2.1.20
在 Gruntfile.js 文件中,使用 grunt.loadNpmTasks 来加载这个任务。git
grunt.loadNpmTasks('grunt-contrib-requirejs');
module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), copy: { dev: { files: [ {expand: true, src: ['src/**/*.js'], dest: 'public/js', filter: 'isFile'} ] } }, requirejs: { compile: { options: { name: "main", baseUrl: "src/js", mainConfigFile: "main.js", out: "public/js/main.js" } } } }); // 加载包含 "copy" 任务的插件。 grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-requirejs'); // 默认被执行的任务列表。 grunt.registerTask('default', ['uglify']); };
compile 是咱们为任务所起名称,options 中是相应的配置。angularjs
在使用这个紧缩任务的时候,默认是不包含 require.js 库的,因此有两种用法。github
第一种用法,只紧缩咱们定义的模块,这样紧缩出来的结果中,会包含 require 过的第三方库,好比 jquery, angularjs 等等,可是不会包含 requirejs 自己。因此,咱们须要在页面中先引用 require.js 库,而后引用咱们紧缩的结果。npm
requirejs: { compile: { options: { name: "main", baseUrl: "src/js", mainConfigFile: "main.js", out: "public/js/main.js" } } }
第二种用法,直接将 require.js 也包含进来,这样,只须要在页面中引用紧缩的结果便可。json
先经过 paths 给 require.js 起一个名称,而后在 include 中包含这个模块。api
//Set paths for modules. If relative paths, set relative to baseUrl above. //If a special value of "empty:" is used for the path value, then that //acts like mapping the path to an empty file. It allows the optimizer to //resolve the dependency to path, but then does not include it in the output. //Useful to map module names that are to resources on a CDN or other //http: URL when running in the browser and during an optimization that //file should be skipped because it has no dependencies. paths: { "requireLib": "lib/require" }, include: ["requireLib"],
在使用 almond 的时候,其实更加简单了。
咱们将 name 设置为 almond 的路径,而后使用 include 将咱们实际的入口模块包含进来就能够了。
这里须要注意一点,almond 是一个独立的脚本库,你须要本身将这个库下载来下,直接使用 bower 就能够。而后,设置 name 为相对于 baseUrl 的 almond 库路径便可。
requirejs: { compile: { options: { baseUrl: "tmp", mainConfigFile: "tmp/main.js", include: "main", name: "../bower_components/almond/almond", out: "tmp/<%= pkg.name %>.js" } } }
注意,上面的官方实例中没有使用 include 包含实际的入口。结果就是不会执行的你的脚本。