relative path doesn't work with paths

2019-02-12 18:08发布

问题:

I'm having a problem with relative paths in requirejs.

First of all, I have the following structure. I'm running it with a virtual host (os.com) and the path is os.com/test

index.html

<script data-main="config" src="require.js"></script>

config.js

require.config({

  baseUrl: "./apps",
  deps: ['ui'],
  paths: {
    ui: 'ui/ui',
    system: 'system/system',
    core: 'core/core'
  }


});

ui.js

define(['./class/menuBuilder',"./class/window"], function(menuBuilder, windowBuilder){


    return {
        menuBuilder: menuBuilder,
        windowBuilder: windowBuilder
    }

});

When I run it, I get the following errors.

GET http://os.com/test/apps/class/menuBuilder.js 404 (Not Found)
GET http://os.com/test/apps/class/window.js 404 (Not Found)

If I take out 'ui' property from the 'paths' property then change deps to ['ui/ui'], it works, but I would like to use paths.

Changed config.js

require.config({

  baseUrl: "./apps",
  deps: ['ui/ui'],
  paths: {
    system: 'system/system',
    core: 'core/core'
  }


});

How do I change my config to make paths and relative path work together?

回答1:

I had similar problem. I didn't have deps:'ui' part in my configuration, just the path setting, but still the relative module reference ('./class/menuBuilder') would not work from the module loaded with path ("ui: 'ui/ui'") and would use baseUrl instead. To solve it, I defined 'ui' as a package:

require.config({

  baseUrl: "./apps",
  deps: ['ui'],
  paths: {
    system: 'system/system',
    core: 'core/core'
  },
  packages : [
    { 
        name: 'ui',
        location : 'ui',
        main : 'ui'
    },
  ]

});

In this case require will load relatively-pathed modules correctly.

Here is a useful post: Relative paths with RequireJS modules/packages



回答2:

The solution here is to use map configuration, not paths configuration. Paths configurations should only be used for folders, not modules themselves. Map configurations apply to individual modules.

So try:

require.config({
  map: {
    '*': {
      'ui': 'ui/ui'
    }
  }
});