Relative paths with RequireJS modules/packages

后端 未结 4 1202
悲哀的现实
悲哀的现实 2021-01-30 02:58

I\'m fairly new to RequireJS and I\'ve run into a bit of a problem. I\'ve written a little framework built on Backbone using RequireJS and I want it to be re-usable in different

4条回答
  •  难免孤独
    2021-01-30 03:23

    You need to define your submodule as package in the require configuration:

    require.config({
      packages: [
        { name: 'packagename',
          location: 'path/to/your/package/root',  // default 'packagename'
          main: 'scriptfileToLoad'                // default 'main' 
        }]
      ... some other stuff ...
    });
    

    To load your module you just need to use your 'packagename' at the requirements:

    define(['jquery', 'packagename'], function($, MyPackage) {
      MyPackage.useIt()
    });
    

    In your package you must use the ./ prefix to load your files relative to your submodule:

    define(['globalDependency', './myLocalFile'], function(Asdf, LocalFile) {
      LocalFile.finallyLoaded();
    });
    

    There is a useful shortcut: If your package name equals to your location and your main file is called 'main.js', then you can replace this

      packages: [
        { name: 'packagename',
          location: 'packagename',
          main: 'main'
        }]
    

    to this:

      packages: ['packagename']
    

    As far as I can see, you already tried to define a package but did you also use the ./ prefix? Without this prefix require will try to find the files in it's global root-path. And without a package, ./ will be useless because the relative path is the same as the global root-path.


    Cheers

提交回复
热议问题