Requirejs: paths vs map

2019-01-25 02:49发布

问题:

Trying to understand where it's right to use "map" with a wildcard vs "paths".

Looking at the require source (but certainly not being 100% fluent with it) it seems like there would functionally be no difference between these two snippets. Is that true?

Using Paths:

  require.config({
    baseUrl: "include/js/",
    paths: {
     foo: "stuff/foo",
    }
  });

Using Map:

  require.config({
    baseUrl: "include/js/",
    map: {
     '*': {foo: "stuff/foo"},
    }
  });

回答1:

From the RequireJS Docs "In addition, the paths config is only for setting up root paths for module IDs, not for mapping one module ID to another one."

This means "paths" is meant for mapping just the path to your resource when it is not in the default location (baseUrl). I guess this is what you were trying to do.

On the other hand, with "map" you can have several versions of your resource (foo1, foo2...) which you can map to be loaded from different paths (i.e. you want to load foo1 from a desktop browser and foo2 which is a modification of the first one from a mobile browser).

So, unless you have different versions of foo I would use "path" although you are right and "map" would also work in that case.



回答2:

I have found one difference, and that's in the case of requirejs loader plugins, example Example: define(['cs!module'], function(){...} ) for CoffeeScript.

Using the map:* part of config for declaring the plugins (and paths for dependent modules) worked in the browser. However, in Node, Requirejs would fail to locate the loader plugins unless they were under paths.

In the end, for the sake of being able to run the same config in Node and the browser, I got rid of the map:* section, and declared everything in paths and it works just fine for me now, even if I'm still hoping to get some clarification on why.



回答3:

There is also one other important difference with the map config. You define a prefix that will be used in mappings.

For your example this would mean that foo will be mapped to stuff/foo but also foo/bar/baz/bam will be mapped to stuff/foo/bar/baz/bam.



标签: requirejs