Skip to content

Instantly share code, notes, and snippets.

@ika18
Last active December 23, 2015 12:49
Show Gist options
  • Save ika18/6637602 to your computer and use it in GitHub Desktop.
Save ika18/6637602 to your computer and use it in GitHub Desktop.
r.js build example in Chinese
/*
* This is an example build file that demonstrates how to use the build system for
* require.js.
*/
({
// 包含你app的顶级文件夹。如果这个选项被使用了,它假定了你的脚本都在这个路径下的子文件夹种。
// 这个是非必要项。如果没有被指定,那下面的baseUrl就是找文件的锚点。
// 如果这个被指定了,那么所有的app目录的文件将被复制到这个路径:
// 输出域和baseUrl会被假定是这个目录下的相对路径。
appDir: "some/path/",
// 默认下,所有的模块位于这个相对路径下。如果baseUrl没有被明确设定,那么所有的模块被加载
// 到相对于有build文件的文件夹中。如果appDir被设置了,那么baseUrl应该被指定为相对于appDir。
baseUrl: "./",
// 默认下,所有的优化配置发生在命令行,或者通过配置文件的属性,并且不考虑app的运行时的配置项
// “main”js文件。但是,如果你更喜欢用“main”js文件的配置做build,那么你不需要在每个配置文件中重复这些值,
// 设置这个属性为main js文件的位置。main js中第一个requirejs({}), require({}), requirejs.config({}),或者
// require.config({})的调用会被使用。
mainConfigFile: '../some/path/to/main.js',
// 设置模块的路径。如果是相对路径,设置相对于以上baseUrl的路径。
// 如果一个特定的"empty:"被作为路径的值,那么它会映射这个路径到一个空文件。它允许优化器解决路径依赖,
// 但是不会把它包括到输入中。映射那些CND的资源模块或者其它的http:的URL模块名称非常有用,当运行在浏览器中和优化过程中,
// 该文件应该被跳过,因为他没有依赖。
paths: {
"foo.bar": "../scripts/foo/bar",
"baz": "../another/path/baz"
},
// 配置CommonJS包,查看看http://requirejs.org/docs/api.html#packages获取更多信息
packages: [],
// 保存输出的文件夹路径。如果没有指定,那么这个路径会默认是一个叫“build”的目录在build文件的同级。
// 所有的相对路径是对于build文件的。
dir: "../some/path",
// 如果shim配置在app运行时使用,这里重复配置。必要的,如果shim配置被使用,因此shim的依赖
// 被加入到构建。使用"mainConfigFile"是一个更好的方法去传这些信息过来,这样只有一个地方被列出来。
// 然而,若mainConfigFile没有,shim配置可以在构建配置加入。
shim: {},
// 在RequireJS 2.0.2中,在构建再次开始前上面的dir将会被删除。如果你有一个大的构建,
// 并且没有做源转换与onBuildRead/onBuildWrite,那么你可以设置keepBuildDir为true
// 保留之前的dir。这允许更快速的重新构建,但是这会导致意想不到的错误,如果构建代码被某种程度的转变了。
keepBuildDir: true,
// 用于内嵌i18n资源加入到构建文件。如果没有地域设置被指定,i18n资源不会被内嵌。
// 对于一个构建只有一个区域可以被内嵌。Root bundles referenced by a build layer
//will be included in a build layer regardless of locale being set.
locale: "en-us",
//How to optimize all the JS files in the build output directory.
//Right now only the following values
//are supported:
//- "uglify": (default) uses UglifyJS to minify the code.
//- "uglify2": in version 2.1.2+. Uses UglifyJS2.
//- "closure": uses Google's Closure Compiler in simple optimization
//mode to minify the code. Only available if running the optimizer using
//Java.
//- "closure.keepLines": Same as closure option, but keeps line returns
//in the minified files.
//- "none": no minification will be done.
// 如何优化所有的JS文件在构建的输出目录中。
// 现在只需要以下几个值被支持
//- "uglify": (默认)使用UglifyJS压缩代码
//- "uglify2": 版本2.1.2以上,使用UglifyJS2
//- "closure": 使用Google的Closure Compiler在简单的优化模式去压缩代码。只在运行优化器使用Java才可用
//- "closure.keepLines": 与closure一样,但是在压缩后的文件中保留换行。
//- "none": 没有压缩
optimize: "uglify",
// 在2.1.2加入:如果对于输出目录使用了“dir”,通常优化设置被用于优化构建束(模块章节配置)
// 和在目录的其它JS文件。但是,如果非构建束的JS文件不会在构建后被加载,你可以跳过这个优化配置
// 来加快构建。设置这个值为true如果你想要跳过优化那些非构建束JS的文件。
skipDirOptimize: false,
// 2.1.2中增加,并作为试验性的。
// 如果压缩器指定了在"otpimize"选项中支持了对压缩后的文件生成source map,则会生产他们。
// 生成的source map只是对压缩的JS翻译到非压缩的JS,它不会对翻译压缩后的文件到源文件做任何神奇的事情。
// 最近仅仅优化项:当运行在node或者rhino中,“Uglify2”会被支持,并且如果在rhino中,“closure”需要一个
// closure comipler jar包构建在r1592(20111114 release)之后。
// 源文件会展示在支持source map的浏览器开发者工具中,名为“.js.src”文件。
generateSourceMaps: false,
// 增加于2.1.1: 如果一个目录的全面优化(“dir”被使用到),并且optimize不是“none”,并且skipDirOptimize是false,
// 那么通常目录中所有的JS文件会被压缩,而且这个值是自动被设为“all”。对于JS文件在压缩后做适当的工作,优化器会解析
// define()调用,并且插入任意的依赖项数组
//Introduced in 2.1.1: If a full directory optimization ("dir" is used), and
//optimize is not "none", and skipDirOptimize is false, then normally all JS
//files in the directory will be minified, and this value is automatically
//set to "all". For JS files to properly work after a minification, the
//optimizer will parse for define() calls and insert any dependency arrays
//that are missing. However, this can be a bit slow if there are many/larger
//JS files. So this transport normalization is not done (automatically set
//to "skip") if optimize is set to "none". Cases where you may want to
//manually set this value:
//1) Optimizing later: if you plan on minifying the non-build bundle JS files
//after the optimizer runs (so not as part of running the optimizer), then
//you should explicitly this value to "all".
//2) Optimizing, but not dynamically loading later: you want to do a full
//project optimization, but do not plan on dynamically loading non-build
//bundle JS files later. In this case, the normalization just slows down
//builds, so you can explicitly set this value to "skip".
//Finally, all build bundles (specified in the "modules" or "out" setting)
//automatically get normalization, so this setting does not apply to those
//files.
normalizeDirDefines: "skip",
//If using UglifyJS for script optimization, these config options can be
//used to pass configuration values to UglifyJS.
//See https://github.com/mishoo/UglifyJS for the possible values.
uglify: {
toplevel: true,
ascii_only: true,
beautify: true,
max_line_length: 1000,
//How to pass uglifyjs defined symbols for AST symbol replacement,
//see "defines" options for ast_mangle in the uglifys docs.
defines: {
DEBUG: ['name', 'false']
},
//Custom value supported by r.js but done differently
//in uglifyjs directly:
//Skip the processor.ast_mangle() part of the uglify call (r.js 2.0.5+)
no_mangle: true
},
//If using UglifyJS for script optimization, these config options can be
//used to pass configuration values to UglifyJS.
//For possible values see:
//http://lisperator.net/uglifyjs/codegen
//http://lisperator.net/uglifyjs/compress
uglify2: {
//Example of a specialized config. If you are fine
//with the default options, no need to specify
//any of these properties.
output: {
beautify: true
},
compress: {
sequences: false,
global_defs: {
DEBUG: false
}
},
warnings: true,
mangle: false
},
//If using Closure Compiler for script optimization, these config options
//can be used to configure Closure Compiler. See the documentation for
//Closure compiler for more information.
closure: {
CompilerOptions: {},
CompilationLevel: 'SIMPLE_OPTIMIZATIONS',
loggingLevel: 'WARNING'
},
//Allow CSS optimizations. Allowed values:
//- "standard": @import inlining, comment removal and line returns.
//Removing line returns may have problems in IE, depending on the type
//of CSS.
//- "standard.keepLines": like "standard" but keeps line returns.
//- "none": skip CSS optimizations.
//- "standard.keepComments": keeps the file comments, but removes line
//returns. (r.js 1.0.8+)
//- "standard.keepComments.keepLines": keeps the file comments and line
//returns. (r.js 1.0.8+)
optimizeCss: "standard.keepLines",
//If optimizeCss is in use, a list of of files to ignore for the @import
//inlining. The value of this option should be a string of comma separated
//CSS file names to ignore (like 'a.css,b.css'. The file names should match
//whatever strings are used in the @import calls.
cssImportIgnore: null,
//cssIn is typically used as a command line option. It can be used
//along with out to optimize a single CSS file.
cssIn: "path/to/main.css",
out: "path/to/css-optimized.css",
//If "out" is not in the same directory as "cssIn", and there is a relative
//url() in the cssIn file, use this to set a prefix URL to use. Only set it
//if you find a problem with incorrect relative URLs after optimization.
cssPrefix: "",
//Inlines the text for any text! dependencies, to avoid the separate
//async XMLHttpRequest calls to load those dependencies.
inlineText: true,
//Allow "use strict"; be included in the RequireJS files.
//Default is false because there are not many browsers that can properly
//process and give errors on code for ES5 strict mode,
//and there is a lot of legacy code that will not work in strict mode.
useStrict: false,
//Specify build pragmas. If the source files contain comments like so:
//>>excludeStart("fooExclude", pragmas.fooExclude);
//>>excludeEnd("fooExclude");
//Then the comments that start with //>> are the build pragmas.
//excludeStart/excludeEnd and includeStart/includeEnd work, and the
//the pragmas value to the includeStart or excludeStart lines
//is evaluated to see if the code between the Start and End pragma
//lines should be included or excluded. If you have a choice to use
//"has" code or pragmas, use "has" code instead. Pragmas are harder
//to read, but they can be a bit more flexible on code removal vs.
//has-based code, which must follow JavaScript language rules.
//Pragmas also remove code in non-minified source, where has branch
//trimming is only done if the code is minified via UglifyJS or
//Closure Compiler.
pragmas: {
fooExclude: true
},
//Same as "pragmas", but only applied once during the file save phase
//of an optimization. "pragmas" are applied both during the dependency
//mapping and file saving phases on an optimization. Some pragmas
//should not be processed during the dependency mapping phase of an
//operation, such as the pragma in the CoffeeScript loader plugin,
//which wants the CoffeeScript compiler during the dependency mapping
//phase, but once files are saved as plain JavaScript, the CoffeeScript
//compiler is no longer needed. In that case, pragmasOnSave would be used
//to exclude the compiler code during the save phase.
pragmasOnSave: {
//Just an example
excludeCoffeeScript: true
},
//Allows trimming of code branches that use has.js-based feature detection:
//https://github.com/phiggins42/has.js
//The code branch trimming only happens if minification with UglifyJS or
//Closure Compiler is done. For more information, see:
//http://requirejs.org/docs/optimization.html#hasjs
has: {
'function-bind': true,
'string-trim': false
},
//Similar to pragmasOnSave, but for has tests -- only applied during the
//file save phase of optimization, where "has" is applied to both
//dependency mapping and file save phases.
hasOnSave: {
'function-bind': true,
'string-trim': false
},
//Allows namespacing requirejs, require and define calls to a new name.
//This allows stronger assurances of getting a module space that will
//not interfere with others using a define/require AMD-based module
//system. The example below will rename define() calls to foo.define().
//See http://requirejs.org/docs/faq-advanced.html#rename for a more
//complete example.
namespace: 'foo',
//Skip processing for pragmas.
skipPragmas: false,
//If skipModuleInsertion is false, then files that do not use define()
//to define modules will get a define() placeholder inserted for them.
//Also, require.pause/resume calls will be inserted.
//Set it to true to avoid this. This is useful if you are building code that
//does not use require() in the built project or in the JS files, but you
//still want to use the optimization tool from RequireJS to concatenate modules
//together.
skipModuleInsertion: false,
//Specify modules to stub out in the optimized file. The optimizer will
//use the source version of these modules for dependency tracing and for
//plugin use, but when writing the text into an optimized bundle, these
//modules will get the following text instead:
//If the module is used as a plugin:
// define({load: function(id){throw new Error("Dynamic load not allowed: " + id);}});
//If just a plain module:
// define({});
//This is useful particularly for plugins that inline all their resources
//and use the default module resolution behavior (do *not* implement the
//normalize() method). In those cases, an AMD loader just needs to know
//that the module has a definition. These small stubs can be used instead of
//including the full source for a plugin.
stubModules: ['text', 'bar'],
//If it is not a one file optimization, scan through all .js files in the
//output directory for any plugin resource dependencies, and if the plugin
//supports optimizing them as separate files, optimize them. Can be a
//slower optimization. Only use if there are some plugins that use things
//like XMLHttpRequest that do not work across domains, but the built code
//will be placed on another domain.
optimizeAllPluginResources: false,
//Finds require() dependencies inside a require() or define call. By default
//this value is false, because those resources should be considered dynamic/runtime
//calls. However, for some optimization scenarios, it is desirable to
//include them in the build.
//Introduced in 1.0.3. Previous versions incorrectly found the nested calls
//by default.
findNestedDependencies: false,
//If set to true, any files that were combined into a build bundle will be
//removed from the output folder.
removeCombined: false,
//List the modules that will be optimized. All their immediate and deep
//dependencies will be included in the module's file when the build is
//done. If that module or any of its dependencies includes i18n bundles,
//only the root bundles will be included unless the locale: section is set above.
modules: [
//Just specifying a module name means that module will be converted into
//a built file that contains all of its dependencies. If that module or any
//of its dependencies includes i18n bundles, they may not be included in the
//built file unless the locale: section is set above.
{
name: "foo/bar/bop",
//For build profiles that contain more than one modules entry,
//allow overrides for the properties that set for the whole build,
//for example a different set of pragmas for this module.
//The override's value is an object that can
//contain any of the other build options in this file.
override: {
pragmas: {
fooExclude: true
}
}
},
//This module entry combines all the dependencies of foo/bar/bop and foo/bar/bee
//and any of their dependencies into one file.
{
name: "foo/bar/bop",
include: ["foo/bar/bee"]
},
//This module entry combines all the dependencies of foo/bar/bip into one file,
//but excludes foo/bar/bop and its dependencies from the built file. If you want
//to exclude a module that is also another module being optimized, it is more
//efficient if you define that module optimization entry before using it
//in an exclude array.
{
name: "foo/bar/bip",
exclude: [
"foo/bar/bop"
]
},
//This module entry shows how to specify a specific module be excluded
//from the built module file. excludeShallow means just exclude that
//specific module, but if that module has nested dependencies that are
//part of the built file, keep them in there. This is useful during
//development when you want to have a fast bundled set of modules, but
//just develop/debug one or two modules at a time.
{
name: "foo/bar/bin",
excludeShallow: [
"foo/bar/bot"
]
},
//This module entry shows the use insertRequire (first available in 2.0):
//if the target module only calls define and does not call require()
//at the top level, and this build output is used with an AMD shim
//loader like almond, where the data-main script in the HTML page is
//replaced with just a script to the built file, if there is no
//top-level require, no modules will execute. specify insertRequire to
//have a require([]) call placed at the end of the file to trigger the
//execution of modules. More detail at
//https://github.com/jrburke/almond
//Note that insertRequire does not affect or add to the modules
//that are built into the build bundle. It just adds a require([])
//call to the end of the built file for use during the runtime
//execution of the built code.
{
name: "foo/baz",
insertRequire: ["foo/baz"]
}
],
//If you only intend to optimize a module (and its dependencies), with
//a single file as the output, you can specify the module options inline,
//instead of using the 'modules' section above. 'exclude',
//'excludeShallow', 'include' and 'insertRequire' are all allowed as siblings
//to name. The name of the optimized file is specified by 'out'.
name: "foo/bar/bop",
include: ["foo/bar/bee"],
insertRequire: ['foo/bar/bop'],
out: "path/to/optimized-file.js",
//An alternative to "include". Normally only used in a requirejs.config()
//call for a module used for mainConfigFile, since requirejs will read
//"deps" during runtime to do the equivalent of require(deps) to kick
//off some module loading.
deps: ["foo/bar/bee"],
//In RequireJS 2.0, "out" can be a function. For single JS file
//optimizations that are generated by calling requirejs.optimize(),
//using an out function means the optimized contents are not written to
//a file on disk, but instead pass to the out function:
out: function (text) {
//Do what you want with the optimized text here.
},
//Wrap any build bundle in a start and end text specified by wrap.
//Use this to encapsulate the module code so that define/require are
//not globals. The end text can expose some globals from your file,
//making it easy to create stand-alone libraries that do not mandate
//the end user use requirejs.
wrap: {
start: "(function() {",
end: "}());"
},
//Another way to use wrap, but uses default wrapping of:
//(function() { + content + }());
wrap: true,
//Another way to use wrap, but uses file paths. This makes it easier
//to have the start text contain license information and the end text
//to contain the global variable exports, like
//window.myGlobal = requirejs('myModule');
//File paths are relative to the build file, or if running a commmand
//line build, the current directory.
wrap: {
startFile: "parts/start.frag",
endFile: "parts/end.frag"
},
//As of r.js 2.1.0, startFile and endFile can be arrays of files, and
//they will all be loaded and inserted at the start or end, respectively,
//of the build bundle.
wrap: {
startFile: ["parts/startOne.frag", "parts/startTwo.frag"],
endFile: ["parts/endOne.frag", "parts/endTwo.frag"]
},
//When the optimizer copies files from the source location to the
//destination directory, it will skip directories and files that start
//with a ".". If you want to copy .directories or certain .files, for
//instance if you keep some packages in a .packages directory, or copy
//over .htaccess files, you can set this to null. If you want to change
//the exclusion rules, change it to a different regexp. If the regexp
//matches, it means the directory will be excluded. This used to be
//called dirExclusionRegExp before the 1.0.2 release.
//As of 1.0.3, this value can also be a string that is converted to a
//RegExp via new RegExp().
fileExclusionRegExp: /^\./,
//By default, comments that have a license in them are preserved in the
//output when a minifier is used in the "optimize" option.
//However, for a larger built files there could be a lot of
//comment files that may be better served by having a smaller comment
//at the top of the file that points to the list of all the licenses.
//This option will turn off the auto-preservation, but you will need
//work out how best to surface the license information.
//NOTE: As of 2.1.7, if using xpcshell to run the optimizer, it cannot
//parse out comments since its native Reflect parser is used, and does
//not have the same comments option support as esprima.
preserveLicenseComments: true,
//Sets the logging level. It is a number. If you want "silent" running,
//set logLevel to 4. From the logger.js file:
//TRACE: 0,
//INFO: 1,
//WARN: 2,
//ERROR: 3,
//SILENT: 4
//Default is 0.
logLevel: 0,
//Introduced in 2.1.3: Some situations do not throw and stop the optimizer
//when an error occurs. However, you may want to have the optimizer stop
//on certain kinds of errors and you can configure those situations via
//this option
throwWhen: {
//If there is an error calling the minifier for some JavaScript,
//instead of just skipping that file throw an error.
optimize: true
},
//A function that if defined will be called for every file read in the
//build that is done to trace JS dependencies. This allows transforms of
//the content.
onBuildRead: function (moduleName, path, contents) {
//Always return a value.
//This is just a contrived example.
return contents.replace(/foo/g, 'bar');
},
//A function that will be called for every write to an optimized bundle
//of modules. This allows transforms of the content before serialization.
onBuildWrite: function (moduleName, path, contents) {
//Always return a value.
//This is just a contrived example.
return contents.replace(/bar/g, 'foo');
},
//A function that is called for each JS module bundle that has been
//completed. This function is called after all module bundles have
//completed, but it is called for each bundle. A module bundle is a
//"modules" entry or if just a single file JS optimization, the
//optimized JS file.
//Introduced in r.js version 2.1.6
onModuleBundleComplete: function (data) {
/*
data.name: the bundle name.
data.path: the bundle path relative to the output directory.
data.included: an array of items included in the build bundle.
If a file path, it is relative to the output directory. Loader
plugin IDs are also included in this array, but dependending
on the plugin, may or may not have something inlined in the
module bundle.
*/
},
//Introduced in 2.1.3: Seed raw text contents for the listed module IDs.
//These text contents will be used instead of doing a file IO call for
//those modules. Useful is some module ID contents are dynamically
//based on user input, which is common in web build tools.
rawText: {
'some/id': 'define(["another/id"], function () {});'
},
//Introduced in 2.0.2: if set to true, then the optimizer will add a
//define(require, exports, module) {}); wrapper around any file that seems
//to use commonjs/node module syntax (require, exports) without already
//calling define(). This is useful to reuse modules that came from
//or are loadable in an AMD loader that can load commonjs style modules
//in development as well as AMD modules, but need to have a built form
//that is only AMD. Note that this does *not* enable different module
//ID-to-file path logic, all the modules still have to be found using the
//requirejs-style configuration, it does not use node's node_modules nested
//path lookups.
cjsTranslate: true,
//Introduced in 2.0.2: a bit experimental.
//Each script in the build bundle will be turned into
//a JavaScript string with a //# sourceURL comment, and then wrapped in an
//eval call. This allows some browsers to see each evaled script as a
//separate script in the script debugger even though they are all combined
//in the same file. Some important limitations:
//1) Do not use in IE if conditional comments are turned on, it will cause
//errors:
//http://en.wikipedia.org/wiki/Conditional_comment#Conditional_comments_in_JScript
//2) It is only useful in optimize: 'none' scenarios. The goal is to allow
//easier built bundle debugging, which goes against minification desires.
// 2.0.2增加:有点试验性
// 构建束中的每个脚本会被转
useSourceUrl: true,
// 定义模块的加载时间。取决于依赖项的复杂度,和库类的大小,增加等待间隔可能是必要的。默认值是7秒。
// 设置为0是禁用等待间隔。
waitSeconds: 7,
// 2.1.9增加:为了避免连接文件和自动分号插入(ASI)规则的的问题,
// 通常,r.js在一个文件的结尾处插入分号,如果那里没有的话。这是安全的非常生硬的修复,但是,
// 如果你想lint构建输出,取决于linter规则,可能不喜欢它。设置这个选项为true,跳过这个插入。
// 但是,这样做,你可以为确保连接代码工作使用JavaScript的ASI规则而负责,
// 你再使用理解何时需要插入分号的压缩工具来避免ASI的陷阱。
skipSemiColonInsertion: false
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment