【发布时间】:2015-06-08 03:15:00
【问题描述】:
鉴于以下简化的场景,我怎样才能最好地构造我的可重用组件,以便它可以被另一个应用程序正确使用,例如 foo.js 打印 23?
可重用组件:
/home.js
/main.js
/stuff
foo.js
--
/home.js:
define([], function () { return 23; }
/stuff/foo.js:
define(['home'], function (home) { console.log(home); } // prints 23
消费者应用:
/app.js
/main.js
/home.js
/views
template.html
/bower_components
/myReusableComponent
/home.js
/main.js
/stuff
foo.js
--
/home.js:
define([], function () { return 17; }
/bower_components/myReusableComponent/home.js:
define([], function () { return 23; }
/bower_components/myReusableComponent/stuff/foo.js:
define(['home'], function (home) { console.log(home); } // now prints 17
是否有消费者应用程序 requirejs 配置将 /myReusableComponent 中任何模块的 baseUrl 设置为“/myReusableComponent”?无论如何,我的可重用组件不应该/不需要访问消费者应用程序的根级别。
我研究了 r.js 优化器,但它只输出一堆 define('stuff/foo', [], function ())...如果消费者应用程序也有一个 stuff/foo.js 会发生什么?
到目前为止,我发现的唯一解决方案是在我的所有模块中强制使用相对路径:define(['../home'], function (home) { console.log(home); },但我希望有更优雅的方法来解决这个问题。
非常感谢所有反馈!
【问题讨论】:
-
我实际上认为在这种情况下相对路径是最好的选择。您也许可以对包做一些事情:requirejs.org/docs/api.html#packages,但我认为这会将正确配置的负担放在消费者身上,这可能会出现问题。
标签: javascript requirejs bower amd