RequireJS中的命名模块与未命名模块 [英] Named module vs Unnamed module in RequireJS

查看:140
本文介绍了RequireJS中的命名模块与未命名模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以在requireJS中创建一个名称:

We can create a module in requireJS by giving it a name:

define("name",[dep],function(dep) {
      // module definition
});

或我们可以创建一个不包括名称:

or we can create one excluding the name:

define([dep],function(dep) {
      // module definition
});

创建模块的更好方法是哪种?我知道RequireJS建议避免分配模块名称。

Which is the better way to create a module? I know RequireJS recommends to avoid assigning module names.

但我想知道在什么情况下我们做什么而不必给模块命名。这会影响使用吗?每种方式的优点和缺点是什么?

But I want to know in what scenarios we do and do not have to give a module a name. Does this affect usage? What are the pros and cons of each way?

推荐答案

这就是requirejs 文档说明命名模块的主题:

This is what the requirejs documentation says on the topic of named modules:


这些通常是由优化工具生成。您可以自己明确命名模块,但它使模块的可移植性降低 - 如果将文件移动到另一个目录,则需要更改名称。通常最好避免使用模块名称进行编码,只需让优化工具在模块名称中进行刻录。优化工具需要添加名称,以便可以在文件中捆绑多个模块,以便在浏览器中加快加载速度。

These are normally generated by the optimization tool. You can explicitly name modules yourself, but it makes the modules less portable -- if you move the file to another directory you will need to change the name. It is normally best to avoid coding in a name for the module and just let the optimization tool burn in the module names. The optimization tool needs to add the names so that more than one module can be bundled in a file, to allow for faster loading in the browser.

但是,假设您想要您的模块有一个众所周知的名称,它允许始终以任何其他模块的相同方式要求它。那么您是否需要使用带名称的 define 调用?一点也不。您可以在配置中使用 路径 : / p>

But let's say you want your module to have a single well-known name that allows always requiring it in the same way from any other module. Do you then need to use the define call with a name? Not at all. You can use paths in your configuration:

paths: {
   'jquery': 'external/jquery-1.9.1',
   'bootstrap': 'external/bootstrap/js/bootstrap.min',
   'log4javascript': 'external/log4javascript',
   'jquery.bootstrap-growl': 'external/jquery.bootstrap-growl',
   'font-awesome': 'external/font-awesome'
},

使用此配置,jQuery可以作为jquery,Twitter Bootstrap为bootstrap等。最佳做法是使用优化器 define >。

With this configuration, jQuery can be required as "jquery", Twitter Bootstrap as "bootstrap", etc. The best practice is to leave calling define with a name to the optimizer.

这篇关于RequireJS中的命名模块与未命名模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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