Search code examples
javascriptrequirejsxregexp

Is XRegExp compatible with RequireJS?


I downloaded RequireJS single page app sample. In the www/lib folder, I put the XRegExp source xregexp-all.js (version 2.0.0).

In www/app/main.js, I added:

var xregexp = require('xregexp-all');
print(typeof(xregexp));

The console output is:

undefined

However, requireJS doesn't emit any error messages. Am I doing something wrong?


Solution

  • Yes, you are doing something wrong. Only some versions of the files distributed for XRegExp perform the required define call that defines them as RequireJS modules. The one you are using does not contain that call. You can determine this for yourself by searching for the define( string in the file.

    You'll need to add a shim to your configuration so that RequireJS can load XRegExp or you'll have to use a version of the file that calls define, like for instance this one which is XRegExp 3.0.0 (still alpha). If you want to use 2.x then your config would be something like:

    paths: {
        xregexp: "../whatever/your/path/actualy/is/xregexp-all"
    }
    
    shim: {
        xregexp: {
          exports: "XRegExp",
        },
    } 
    

    Note that this config normalizes the module name to xregexp, so you would have to require it as xregexp, not xregexp-all. In general, I prefer not to have things like -all or .min in my module names since these may change depending on the situation.

    The shim tells RequireJS that the value it should export when xregexp is required is that of the global symbol XRegExp. This is generally how you handle modules that are not AMD-aware.