在 RequireJS 和 Node 共用模块的想法
发布于 12 年前 作者 jiyinyiyong 10987 次预览 最后一次回复是 12 年前 来自
前后端都有模块化机制, 但两个不兼容, 这件事情非常纠结, 耽误大量时间. SeaJS 和 RequireJS 采用的模块化方案, 答题上兼容了 CommonJS, 但是细节上, 有个 Wrapper, 比如模块在 Node 里这样写的
a = require "b"
exports.c = ->
c
var a;
a = require("b");
exports.c = function() {
return c;
};
需要写成
define (require, exports) ->
a = require "b"
exports.c = ->
c
define(function(require, exports) {
var a;
a = require("b");
return exports.c = function() {
return c;
};
});
define 是在代码加载完成以后异步调用的函数主体的…
想来想去没有明确的方案, 现在有个想法
main = (dep1, exports) ->
exports.api = ->
"demo"
if define?
define (require, exports) ->
dep1 = require "./dep1"
main dep1, exports
else if exports?
dep1 = require "./dep1"
main dep1, exports
(function() {
var dep1, main;
main = function(dep1, exports) {
return exports.api = function() {
return "demo";
};
};
if (typeof define !== "undefined" && define !== null) {
return define(function(require, exports) {
var dep1;
dep1 = require("./dep1");
return main(dep1, exports);
});
} else if (typeof exports !== "undefined" && exports !== null) {
dep1 = require("./dep1");
return main(dep1, exports);
}
})();
模块的定义和加载, 似乎是可以解决的, RequireJS 打包方面不知道会不会有问题… 给点建议?
9 回复
这方面大家已经做得很多了,http://ryanflorence.com/2013/es6-modules-and-browser-app-delivery/
UMD 我不赞同, 我认为是找了个产品环境能用的方案, 继续 leave core problems unsovled.
目前,觉得,各写各个的更好…
常用方法, 比如数组, 字符串, 这些纯数据的逻辑在两个平台完全共通的, 单写一个平台没必要扯上两边, 但写一个模块给两边用就麻烦比较大了. 没有完整方案, 只能 Hack 呀
根据
define,exports等是否可用来判断执行环境没啥问题。 比如在 ant.js中,我大概是这么写的:兼容 nodeJs,amd,cmd。
具体使用的问题会有不?
…发现太晚了, 原来双向绑定已经快烂大街了
@jiyinyiyong 各个模块规范的
require,exports,module的用法基本一致。 AMD 和 CMD 的define也可以使用同一种factory函数, 所以不会有问题。@jiyinyiyong 烂大街了
@island205 Cirru 这边完了继续学双向绑定… 还没想明白怎么自己实现, 你是从哪儿跟上去的呀?