目前,我通过谷歌闭包编译器使用了一些defines,就像IS_CJS和IS_BROWSER一样,只是构建了不同的文件(browser.myproject.js、cjs.myproject.js等)。
这是做事情的标准方法吗?如果没有,它是什么?它的优势是什么?
发布于 2011-09-20 00:10:18
我一直在我的所有项目中使用以下前言,用于由浏览器和服务器代码加载的库:
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>)调用以及使用RequireJS的require(<library>)调用来加载库。在浏览器上,嵌套的require调用在库执行之前由RequireJS预取,在节点上,这些依赖项被同步加载。因为我没有使用我的库作为独立的脚本(通过html中的script标签),而只是作为通过script标签加载的脚本的依赖项,所以这对我很有效。
然而,看看独立库,看起来下面的前言似乎是最灵活的。(从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;
});虽然冗长,但它非常灵活,而且无论您的执行环境是什么,它都能简单地工作。
发布于 2014-04-01 18:38:39
您可以使用uRequire,通过模板系统将用AMD或CommonJS编写的模块转换为AMD、CommonJS或UMD。
uRequire可以选择将整个捆绑包构建为在所有环境(nodejs、AMD或无模块浏览器< combinedFile.js />)中运行的脚本,这将在幕后使用rjs优化器和almond。
uRequire 使您不必在每个模块中维护任何样板-只需编写简单的AMD或CommonJS模块(如.js、.coffee、.coco、.ls等),而不会有花招。
此外,您可以声明性地将标准功能(如exporting a module )与noConflict()方法一起添加到全局(如window.myModule )中,或者在构建时使用runtimeInfo (eg __isNode, __isAMD) selectively或替换/移除/注入依赖项,自动缩小、操作模块代码等。
所有这些configuration options都可以在每个包或每个模块中打开和关闭,并且您可以拥有彼此派生(继承)的不同构建配置文件(开发、测试、生产等)。
它可以很好地通过grunt-urequire或独立的grunt工作,并且它有一个很棒的watch选项,可以只重建更改过的文件。
发布于 2012-12-09 01:26:57
你试过这个吗:https://github.com/medikoo/modules-webmake#modules-webmake?
这是我正在采取的方法,它真的很好用。代码中没有样板,您可以在服务器端和客户端运行相同的模块
https://stackoverflow.com/questions/6665779
复制相似问题