requireJS configuration for Modernizr

jantimon picture jantimon · Aug 7, 2013 · Viewed 13.4k times · Source

I am trying to load the Modernizr feature detects dynamically with requireJS.
As Modernizr has built in AMD support this shouldn't be a problem.

My requireJS configuration contains the paths to the Modernizr source directory and to the feature detects directory:

requirejs.config({
  paths: {
    "modernizr" : "components/modernizr/src",
    "feature-detects": "components/modernizr/feature-detects"
  }
});

Lets assume one of my views would require the svg test.
My view definition might look like this

define(["feature-detects/svg"], function() { .. });

Unfortunately the svg.js can't find Modernizr.js because all feature detects and Modernizr source files load Modernizr without specifying any directory: define(['Modernizr'], ...

Which results in a very ugly require.config

requirejs.config({
  paths: {
    "Modernizr": "components/modernizr/src/Modernizr",
    "addTest": "components/modernizr/src/addTest",
    "ModernizrProto": "components/modernizr/src/ModernizrProto",
    "setClasses": "components/modernizr/src/setClasses",
    "hasOwnProp": "components/modernizr/src/hasOwnProp",
    "tests": "components/modernizr/src/tests",
    "is": "components/modernizr/src/is",
    "docElement": "components/modernizr/src/docElement",
    "feature-detects": "components/modernizr/feature-detects"
  }
});

Is there a cleaner way to tell requireJS to search in components/modernizr/src/ whenever it couldn't find the file?

Update

I created an example github project which includes the basic setup and a running demonstration.

Answer

Stu Cox picture Stu Cox · Aug 14, 2013

Modernizr's AMD structure is (currently) just for its own internal build process. We've discussed exposing this so that it can be used as you've tried, but haven't agreed on a convenient way to do this yet. A Modernizr plugin for RequireJS could be one option.

Are you using Bower? If so, it's worth noting Modernizr isn't suitable for use with Bower yet.

The recommended way to tie Modernizr into your build process at the moment is using grunt-modernizr, which will automatically find references to Modernizr detects in your code (or you can explicitly define them), then you can just use the resulting Modernizr build like any other AMD dependency whenever you need it:

define(['path/to/built/modernizr.js'], function (Modernizr) {
    if (Modernizr.svg) {
        ...
    }
});