No dependencies defined when they are loaded via absolute paths

依然范特西╮ 提交于 2019-12-12 02:05:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!