Javascript 跨公共JS/浏览器开发的最佳实践
目前,我通过Google Closure编译器使用了一些Javascript 跨公共JS/浏览器开发的最佳实践,javascript,node.js,cross-platform,commonjs,Javascript,Node.js,Cross Platform,Commonjs,目前,我通过Google Closure编译器使用了一些定义,大致是IS_CJS和IS_BROWSER,只是生成了不同的文件(BROWSER.myproject.js,CJS.myproject.js,等等) 这是做事情的标准方式吗?如果没有,它是什么?它的优点是什么?我在所有项目中都使用了以下序言,用于同时由浏览器和服务器代码加载的库: if (define === undefined) { var define = function(f) { require.
定义
,大致是IS_CJS
和IS_BROWSER
,只是生成了不同的文件(BROWSER.myproject.js
,CJS.myproject.js
,等等)
这是做事情的标准方式吗?如果没有,它是什么?它的优点是什么?我在所有项目中都使用了以下序言,用于同时由浏览器和服务器代码加载的库:
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 };
...
});
虽然冗长,但无论您的执行环境是什么,它都非常灵活,而且简单有效。您是否尝试过以下方法:
这是我正在采取的方法,而且效果非常好。代码中没有样板文件,您可以在服务器端和客户端运行相同的模块您可以使用它通过模板系统将用AMD或CommonJS编写的模块转换为AMD、CommonJS或UMD
(可选)uRequire将您的整个捆绑包构建为一个combinedFile.js
,在使用rjs optimizer和引擎盖下的所有环境(nodejs、AMD或无模块浏览器)中运行
uRequire使您无需在每个模块中维护任何样板文件,只需编写简单的AMD或CommonJS模块(如.js、.coffee、.coco、.ls等),而无需任何技巧
此外,您还可以声明性地添加标准功能,例如到全局,例如window.myModule
以及noConflict()
方法,或者在构建、自动缩小、操作模块代码等过程中拥有或替换/删除/注入依赖项
所有这些都可以在每个bundle或每个模块中打开和关闭,并且您可以拥有彼此派生(继承)的不同构建概要文件(开发、测试、生产等)
它可以通过grunt或单机版运行,并且有一个很好的选项,可以只重建已更改的文件。我不喜欢使用r.js RequireJS适配器,我希望人们能够使用我自己创建的库。我使用的是基于RequireJS提供的手动转换现有CommonJS模块的功能,在这里可以找到:区别在于,我添加了一个在CommonJS中执行的函数,这样它既可以在CommonJS环境中工作,也可以在RequireJSGotcha中工作。我们不得不使用这样的乱七八糟的东西,真是令人伤心(好吧,CommonJS将转向一种不太异步的模块语法(允许您通过函数而不是在一个简单的
导出
全局上定义模块导出)。因此,我们可以使用wcross环境库。
(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;
});