Tomasz Grobelny
Tomasz Grobelny

Reputation: 2746

multifile javascript library

I am writing a library that will consist of multiple modules/files. One of the files (let's call it Main) will depend on all other files and so when the user loads this file then the whole library will get loaded.

Now the user may place all of my library in a subfolder (let's call it subdir1), so he configures requirejs like this:

require.config({
    paths: {
        "jquery": "Scripts/jquery-2.0.3.min",
        "knockout": "Scripts/knockout-2.3.0",
        "MyLib.Main": "subdir1/MyLib.Main"
    }
});

In this scenario the subdir1/MyLib.Main.js file will load just fine, but if this file depends on MyLib.Helper module then requirejs will try to load it from MyLib.Helper.js and not subdir1/MyLib.Helper.js file where it is located.

Is there any way to tell requirejs to load submodules from subdir1? I know I can enumerate all those modules in config, but that requires the end-user to know the internal structure of my library (which is not acceptable). Ideally I should be able to enumerate all modules that should be loaded from subdir1 inside MyLib.Main.js file somehow (but note that at this point I cannot hardcode that it will be subdir1).

Upvotes: 1

Views: 109

Answers (1)

Willem D'Haeseleer
Willem D'Haeseleer

Reputation: 20180

Ask your user to configure a LIBNAME_PATH variable in his require config Then use this path variable to prefix all your paths

Example:

require.config({
    paths: {
        "jquery": "Scripts/jquery-2.0.3.min",
        "knockout": "Scripts/knockout-2.3.0",
        "MyLib_PATH": "subdir1",
        "MyLib.Main": "subdir1/MyLib.Main"
    }
});

Then in subdir1/MyLib.Main, you might have something like this:

require.config({
    paths: {
        "MyLib.Helper": "MyLib_PATH/MyLib.Helper"  
    }
});

requirejs should then resolve MyLib_PATH to the right path as configured by the user.

This is a super untested draft but i think it should work. This does imply you have to use this LIBNAME_PATH everywhere in your library.

Upvotes: 1

Related Questions