问题
I have some module like this:
define('hello',[],
function()
{
return {
say: function(word) { console.log("Hello, "+word) },
};
});
And I'm using it like this (without any require.config) :
require(["hello"],
function(hello)
{
console.log("main",hello);
hello.say("main");
});
So far, so good.
But when I'm trying to require the same module with an absolute path, I've got my dependence module undefined:
require(["http://example.com/js/hello.js"],
function(hello)
{
console.log("main",hello);
hello.say("main");
});
Console:
main undefined
Uncaught TypeError: Cannot read property 'say' of undefined // Oops!
Why is it so?
回答1:
Named module (define("NAME", [ ... ], function() { ... })) is meant to be required under exact that name. When it is required with a URL it is loaded correctly, but registers itself under its "desired" name, after which requirejs loses track of it still looking for a module with a name http://example.com/js/hello.js.
The reason the name given to define() isn't overriden with the one under which the module was required is to allow multiple module definitions to coexist in the file, for example after optimization. Optimizer will convert all define calls to the form with explicit name.
The reason the absolute name isn't converted to a module id is that this conversion is impossible. All the configuration options of requirejs determine how to convert module id to script location, not other way around.
Documentation discourages use of the named modules:
These are normally generated by the optimization tool. You can explicitly name modules yourself, but it makes the modules less portable ... It is normally best to avoid coding in a name for the module and just let the optimization tool burn in the module names...
Anonymous module, i.e.:
define([],
function()
{
return {
say: function(word) { console.log("Hello, "+word) },
};
});
works with either module id ("hello") or absolute path, because it is first registered without a name and later receives the name under which it was required.
来源:https://stackoverflow.com/questions/26404315/no-dependencies-defined-when-they-are-loaded-via-absolute-paths