Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

javascript - Named module vs Unnamed module in 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
});

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?

question from:https://stackoverflow.com/questions/19720646/named-module-vs-unnamed-module-in-requirejs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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'
},

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...