RequireJS Optimizer 的使用和配置

RequireJS Optimizer 的配置參數還有很多,完整的參數介紹可以看這裏:

https://github.com/jrburke/r.js/blob/master/build/example.build.js

http://www.cnblogs.com/didi/p/4146656.html


基本參數介紹:

appDir:

應用程序的最頂層目錄。可選的,如果設置了的話,r.js 會認爲腳本在這個路徑的子目錄中,應用程序的文件都會被拷貝到輸出目錄(dir 定義的路徑)。如果不設置,則使用下面的 baseUrl 路徑。

baseUrl:

默認情況下,所有的模塊都是相對於這個路徑的。如果沒有設置,則模塊的加載是相對於 build 文件所在的目錄。另外,如果設置了appDir,那麼 baseUrl 應該定義爲相對於 appDir 的路徑。

dir:

輸出目錄的路徑。如果不設置,則默認爲和 build 文件同級的 build 目錄。

optimize:

JavaScript 代碼優化方式。可設置的值:
"uglify:使用 UglifyJS 壓縮代碼,默認值;
"uglify2":使用 2.1.2+ 版本進行壓縮;
"closure": 使用 Google's Closure Compiler 進行壓縮合並,需要 Java 環境;
"closure.keepLines":使用 Closure Compiler 進行壓縮合並並保留換行;
"none":不做壓縮合並;

optimizeCss:

CSS 代碼優化方式,可選的值有:
"standard":標準的壓縮方式;
"standard.keepLines":保留換行;
"standard.keepComments":保留註釋;
"standard.keepComments.keepLines":保留換行;
"none":不壓縮;

mainConfigFile:

如果不想重複定義的話,可以使用這個參數配置 RequireJS 的配置文件路徑。

removeCombined:

刪除之前壓縮合並的文件,默認值 false。

fileExclusionRegExp:

要排除的文件的正則匹配的表達式。

modules:

定義要被優化的模塊數組。每一項是模塊優化的配置,常用的幾個參數如下:
name:模塊名;
create:如果不存在,是否創建。默認 false;
include:額外引入的模塊,和 name 定義的模塊一起壓縮合並;
exclude:要排除的模塊。有些模塊有公共的依賴模塊,在合併的時候每個都會壓縮進去,例如一些基礎庫。使用 exclude 就可以把這些模塊在壓縮在一個更早之前加載的模塊中,其它模塊不用重複引入。



r.js 參數


/*
 * This is an example build file that demonstrates how to use the build system for
 * require.js.
 *
 *
 * r.js 配置文件 example.build.js 不完整註釋\
 * 結合最近打包實踐,對這個 r.js 下的 build 配置文件作了些補充說明:
 *
 *
 * THIS BUILD FILE WILL NOT WORK. It is referencing paths that probably
 * do not exist on your machine. Just use it as a guide.
 *
 *
 */

({
    // app頂級目錄,非必選項。如果指定值,baseUrl則會以此爲相對路徑
    appDir: "some/path/",

    // 模塊根目錄。默認情況下所有模塊資源都相對此目錄。
    // 若該值未指定,模塊則相對build文件所在目錄。
    // 若appDir值已指定,模塊根目錄baseUrl則相對appDir。
    baseUrl: "./",

    // 配置文件目錄
    mainConfigFile: '../some/path/to/main.js',

    // 設置模塊別名
    // RequireJS 2.0 中可以配置數組,順序映射,當前面模塊資源未成功加載時可順序加載後續資源
    paths: {
        "foo.bar": "../scripts/foo/bar",
        "baz": "../another/path/baz"
    },

    // 配置 CommonJS 的 package See http://requirejs.org/docs/api.html#packages for more information.
    packagePaths: [],
    packages: [],

    // 指定輸出目錄,若值未指定,則相對 build 文件所在目錄
    dir: "../some/path",

    // 在 RequireJS 2.0.2 中,輸出目錄的所有資源會在 build 前被刪除
    // 值爲 true 時 rebuild 更快,但某些特殊情景下可能會出現無法預料的異常
    keepBuildDir: true,

    // 國際化配置
    locale: "en-us",

    // JS 文件優化方式,目前支持以下幾種:
    //   uglify: (默認) 使用 UglifyJS 來壓縮代碼
    //   closure: 使用 Google's Closure Compiler 的簡單優化模式
    //   closure.keepLines: 使用 closure,但保持換行
    //   none: 不壓縮代碼
    optimize: "uglify",

    // 使用 UglifyJS 時的可配置參數
    // See https://github.com/mishoo/UglifyJS for the possible values.
    uglify: {
        toplevel: true,
        ascii_only: true,
        beautify: true,
        max_line_length: 1000
    },

    // 使用 Closure Compiler 時的可配置參數
    closure: {
        CompilerOptions: {},
        CompilationLevel: 'SIMPLE_OPTIMIZATIONS',
        loggingLevel: 'WARNING'
    },

    // CSS 優化方式,目前支持以下幾種:
    // none: 不壓縮,僅合併
    // standard: 標準壓縮,移除註釋、換行,以及可能導致 IE 解析出錯的代碼
    // standard.keepLines: 除標準壓縮外,保留換行
    // standard.keepComments: 除標準壓縮外,保留註釋 (r.js 1.0.8+)
    // standard.keepComments.keepLines: 除標準壓縮外,保留註釋和換行 (r.js 1.0.8+)
    optimizeCss: "standard.keepLines",

    // 是否忽略 CSS 資源文件中的 @import 指令
    cssImportIgnore: null,

    // 一般用於命令行,可將多個 CSS 資源文件打包成單個 CSS 文件
    cssIn: "path/to/main.css",
    out: "path/to/css-optimized.css",

    // 處理所有的文本資源依賴項,從而避免爲加載資源而產生的大量單獨xhr請求
    inlineText: true,

    // 是否開啓嚴格模式
    // 由於很多瀏覽器不支持 ES5 的嚴格模式,故此配置默認值爲 false
    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
    },

    // 命名空間,完整實例可以參考 http://requirejs.org/docs/faq-advanced.html#rename
    namespace: 'foo',

    // 跳過 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 layer, 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,

    // 處理級聯依賴,默認爲 false,此時能夠在運行時動態 require 級聯的模塊。爲 true 時,級聯模塊會被一同打包
    findNestedDependencies: false,

    //If set to true, any files that were combined into a build layer will be
    //removed from the output folder.
    removeCombined: false,

    modules: [
        {
            // 模塊 alias 名稱
            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
                }
            }
        },

        // 將 alias 別名爲 foo/bar/bop 和 foo/bar/bee 的模塊打包成一個文件
        {
            name: "foo/bar/bop",
            include: ["foo/bar/bee"]
        },

        // 將 foo/bar/bip 及其依賴項一併打包,但不包括 foo/bar/bop
        {
            name: "foo/bar/bip",
            exclude: [
                "foo/bar/bop"
            ]
        },

        // 排除指定模塊,但若該模塊對所打包文件有級聯依賴關係,則仍會被打包進去
        {
            name: "foo/bar/bin",
            excludeShallow: [
                "foo/bar/bot"
            ]
        },

        // insertRequire 在 RequireJS 2.0 中被引入,在 built 文件的末尾插入 require([]) 以觸發模塊加載並運行
        // insertRequire: ["foo/baz"] 即 require(["foo/baz"])
        // 詳情見 https://github.com/jrburke/almond
        {
            name: "foo/baz",
            insertRequire: ["foo/baz"]
        }
    ],

    // 僅優化單個模塊及其依賴項
    name: "foo/bar/bop",
    include: ["foo/bar/bee"],
    insertRequire: ['foo/bar/bop'],
    out: "path/to/optimized-file.js",

    // An alternative to "include"
    deps: ["foo/bar/bee"],

    // RequireJS 2.0 中,out 可以是一個函數
    out: function (text) {
        // 自定義優化內容
    },

    // 模塊包裹函數,顧名思義使用特定內容包裹模塊,如此一來 define/require 就不再是全局變量,在 end 中可以暴露一些全局變量供整個函數使用
    wrap: {
        start: "(function() {",
        end: "}());"
    },

    // 另一種模塊包裹方式
    // (function() { + content + }());
    wrap: true,

    // 另一種模塊包裹方式,包裹內容可以是指定文件
    wrap: {
        startFile: "part/start.frag",
        endFile: "parts/end.frag"
    },

    // 不優化某些文件
    fileExclusionRegExp: /^\./,

    // 默認保留模塊的 license 註釋
    preserveLicenseComments: true,

    // 設置 logging level
    // TRACE: 0,
    // INFO: 1,
    // WARN: 2,
    // ERROR: 3,
    // SILENT: 4
    // Default is 0.
    logLevel: 0,

    // 在每個文件模塊被讀取時的操作函數,可在函數體內作適當變換
    onBuildRead: function (moduleName, path, contents) {
        return contents.replace(/foo/g, 'bar');
    },

    // 在每個文件模塊被寫入時的操作函數
    onBuildWrite: function (moduleName, path, contents) {
        return contents.replace(/bar/g, 'foo');
    },

    // 若爲true,優化器會強制在文件中包裹一層 define(require, exports, module) {})
    cjsTranslate: true,

    //Introduced in 2.0.2: a bit experimental.
    //Each script in the build layer 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 layer debugging, which goes against minification desires.
    useSourceUrl: true
})












發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章