创建一个可重用的RequireJs库 [英] Creating a reusable RequireJs library

查看:95
本文介绍了创建一个可重用的RequireJs库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到以下简化情况,我如何最好地构造我的可重用组件,以便它可以被另一个应用程序正确使用,例如foo.js可以显示23?

Given the following simplified scenario, how could I best construct my reusable component so that it is correctly consumable by another application, such that foo.js prints 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'?无论如何,我的可重用组件都不应/不需要访问使用者应用程序的根级别.


Is there a consumer application requirejs config that sets the baseUrl of any module in /myReusableComponent to '/myReusableComponent'? My reusable component should not have/need access to the root level of the consumer application anyway.

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

I have looked into the r.js optimizer, but it just outputs a bunch of define('stuff/foo', [], function ())... what happens if the consumer application has a stuff/foo.js too?

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

The only solution I have found so far is forcing the use of relative paths in all of my modules: define(['../home'], function (home) { console.log(home); } but I am hoping there is a more elegant way to solve this problem.

非常感谢所有反馈!

推荐答案

如果要生成将在不同应用程序中使用的库,则当库的一个模块引用另一个模块时,应使用相对路径,因为这使得使用您的库的人更有可能无需修改自己的RequireJS配置就可以这样做.

If you want to produce a library that is going to be usable in different applications, then you should use use relative paths when one module of your library refers to another, because this makes it more likely that whoever uses your library will be able to do so without having to do modify their RequireJS configuration.

通过明智地使用mappaths可以消除某些冲突.但是,最终,有些情况下如果无法访问未优化的模块就无法解决(或至少无法按照用户的需要解决),因此您应将库作为优化的软件包分发可以将其作为未优化模块的集合进行加载.

Some clashes can be eliminated by the judicious use of map or paths. Ultimately, however, there are cases that cannot be solved (or at least not be solved as the user wants it) without having access to the unoptimized modules so you should distribute your library as an optimized bundle and provide the possibility to load it as a collection of unoptimized modules.

这篇关于创建一个可重用的RequireJs库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆