Search code examples
modulerequirejsbrowser-feature-detection

Create multiple builds of the same require.js module


Using require.js and r.js, lets say I have a module, "myModule.js".

The r.js docs state that they support integration with has.js such that

has: {
     feature: true
}

transforms something like:

if (has('feature')) {
     alert('feature detected!');
} else {
     alert('feature not supported')
}

to:

alert('feature detected!');

However, how can I go about creating two versions of the same module? One version for those browsers that support the feature and another version for those browsers that do not support the feature.


Solution

  • Let's say your entry point to your application is named app. You could create a module app-has-foo where the feature foo is true and app-no-foo where it is false. You have to use create so that r.js knows it has to create the modules. You use override to override those options that belong outside the modules option.

    ({
        baseUrl: ...,
        mainConfigFile: ...,
        dir: "out",
        modules: [
            {
                name: "app-has-foo",
                create: true,
                include: ["app"],
                override: {
                    has: {
                        foo: true
                    }
                }
            },
            {
                name: "app-no-foo",
                create: true,
                include: ["app"],
                override: {
                    has: {
                        foo: false
                    }
                }
            }
        ]
    });