1

目前,我defines通过 Google Closure Compiler使用了一些类似IS_CJSand的方法IS_BROWSER,并且只是构建了不同的文件(browser.myproject.js,cjs.myproject.js等)。

这是做事的标准方式吗?如果不是,它是什么,有什么优势?

4

3 回答 3

2

对于由浏览器和服务器代码加载的库,我在所有项目中都使用了以下序言:

if (define === undefined) {
    var define = function(f) {
            require.paths.unshift('.');
            f(require, exports, module);
        };
}

define(function(require, exports, module) {
    ...
    // main library here
    ...
    // use require to import dependencies
    var v = require(something);
    ...
    // use exports to return library functions
    exports.<stuff> = { some stuff };
    ...
});

require(<library>)这可以通过在我的节点服务器上运行的require(<library>)调用以及使用RequireJS的调用来加载库。在浏览器上,嵌套require调用在库执行之前由 RequireJS 预取,在 Node 上,这些依赖项是同步加载的。由于我没有将我的库用作独立脚本(通过 html 中的脚本标记),并且仅作为通过脚本标记加载的脚本的依赖项,因此这对我来说效果很好。


但是,查看独立库,看起来下面的序言似乎是最灵活的。(从 Q Promise 库中剪切和粘贴

(function (definition, undefined) {

    // This file will function properly as a <script> tag, or a module
    // using CommonJS and NodeJS or RequireJS module formats.  In
    // Common/Node/RequireJS, the module exports the Q API and when
    // executed as a simple <script>, it creates a Q global instead.

    // The use of "undefined" in the arguments is a
    // micro-optmization for compression systems, permitting
    // every occurrence of the "undefined" variable to be
    // replaced with a single-character.

    // RequireJS
    if (typeof define === "function") {
        define(function (require, exports, module) {
            definition(require, exports, module);
        });
    // CommonJS
    } else if (typeof exports === "object") {
        definition(require, exports, module);
    // <script>
    } else {
        Q = definition(undefined, {}, {});
    }

})(function (serverSideRequire, exports, module, undefined) {

    ...
    main library here
    ... 


/*
 * In module systems that support ``module.exports`` assignment or exports
 * return, allow the ``ref`` function to be used as the ``Q`` constructor
 * exported by the "q" module.
 */
for (var name in exports)
    ref[name] = exports[name];
module.exports = ref;
return ref;

});

虽然冗长,但无论您的执行环境是什么,它都非常灵活,而且工作简单。

于 2011-09-19T16:10:17.643 回答
1

您可以使用uRequire通过模板系统将用 AMD 或 CommonJS 编写的模块转换为 AMD、CommonJS 或 UMD。

可选地,uRequire 将您的整个捆绑包构建为combinedFile.js在所有环境(nodejs、AMD 或无模块浏览器 < script/>)中运行,即使用 rjs 优化器和 almond引擎盖下。

uRequire 使您不必在每个模块中维护任何样板文件 - 只需编写普通的 AMD 或 CommonJS 模块(如 .js、.coffee、.coco、.ls 等),无需任何噱头。

另外,您可以声明性地添加标准功能,例如将模块导出到全局(例如window.myModulenoConflict()方法一起),或者有选择地使用runtimeInfo(例如 __isNode、__isAMD),或者在构建、自动缩小、操作模块代码等时替换/删除/注入依赖项更多的。

所有这些配置选项都可以按包或每个模块打开和关闭,并且您可以拥有彼此派生(继承)的不同构建配置文件(开发、测试、生产等)。

它可以通过grunt-urequire或独立的方式与 grunt 一起工作,并且它有一个很棒的watch选项,可以只重建更改的文件。

于 2014-04-01T10:38:39.010 回答
0

您是否尝试过:https ://github.com/medikoo/modules-webmake#modules-webmake ?

这是我正在采取的方法,而且效果很好。代码中没有样板,您可以在服务器端和客户端运行相同的模块

于 2012-12-08T17:26:57.467 回答