[英]Isomorphic JavaScript with RequireJS
I have some isomorphic JavaScript. 我有一些同构JavaScript。 I am using RequireJS on the client side. 我在客户端使用RequireJS。
(function() {
'use strict';
function wrapper(require) {
var MyDep = require('my-dependency');
return function MyExportedFunction() {
// ...
};
}
if ((typeof exports === 'object') && module) {
module.exports = wrapper(require); // CommonJS
} else if ((typeof define === 'function') && define.amd) {
define(function(require) {
/**
* I need to `require` dependencies
* in here for them to be available inside
* the wrapper function :(
*/
require('my-dependency');
return wrapper(require);
}); // AMD
}
}());
Is there a way to circumvent having to place the require
statment positioned immediately before the wrapper
function invocation? 有没有一种方法可以避免必须在wrapper
函数调用之前放置require
语句?
If I omit that require
statement, RequireJS complains that the dependency has not yet been loaded for the context. 如果我省略了require
语句,RequireJS会抱怨尚未为上下文加载依赖项。
I presume this is an insurmountable limitation of RequireJS' ability to parse and identify require'd dependencies ahead of time. 我认为这是RequireJS提前解析和识别需求依赖项的能力的不可克服的局限。
Yeah, RequireJS can only handle the CommonJS form of require
only if it is present immediately in the factory function passed to define
. 是啊,RequireJS只能处理CommonJS的形式的require
,只有当它是在传递给工厂函数直接呈现的define
。 If it appears in functions called from the factory function but that are defined outside the function, then it won't work. 如果它出现在从工厂函数调用的函数中,但在函数外部定义,则它将不起作用。 Internally, RequireJS runs a regular expression on the factory function's source. 在内部,RequireJS在工厂函数的源代码上运行正则表达式。
This being said, it seems to me you should be able to replace your current call to define
with: 话虽这么说,在我看来,您应该可以用以下命令替换当前define
调用:
define(wrapper)
This will call wrapper
with a reference to RequireJS' require
function and RequireJS should be able to analyze the source of wrapper
to extract the CommonJS calls. 这将使用对RequireJS的require
函数的引用来调用wrapper
, 并且 RequireJS应该能够分析wrapper
的来源以提取CommonJS调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.