创建可重用的RequireJs库

时间:2015-04-03 02:09:38

标签: javascript requirejs bower amd

鉴于以下简化方案,我如何才能最好地构建我的可重用组件,以便其他应用程序可以正确使用它,以便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 config将/ myReusableComponent中任何模块的baseUrl设置为' / myReusableComponent'?无论如何,我的可重用组件不应该/需要访问消费者应用程序的根级别。

我已经查看了r.js优化器,但它只输出了一堆define('stuff/foo', [], function ()) ...如果消费者应用程序也有一个东西/ foo.js会发生什么?

到目前为止我找到的唯一解决方案是强制在我的所有模块中使用相对路径:define(['../home'], function (home) { console.log(home); }但我希望有更优雅的方法来解决这个问题。

非常感谢所有反馈!

1 个答案:

答案 0 :(得分:0)

如果您想要生成一个可以在不同应用程序中使用的库,那么当您的库中的一个模块引用另一个模块时,您应该使用相对路径,因为这使得使用您的库的任何人都更有可能能够这样做,而无需修改他们的RequireJS配置。

明智地使用mappaths可以消除一些冲突。但是,最终有些情况无法解决(或者至少不能按用户的意愿解决)而无法访问未经优化的模块,因此您应该将库分发为优化的包提供可以将其作为未优化模块的集合加载。

相关问题