Search code examples
javascriptxregexp

How can I load XRegExp only with a few addons?


I've searched XRegExp's web site, and the GitHub readme. The only examples there load xregexp-all.js, which is exactly what I don't want to do because it loads all the addons. Searching on SO, I found examples like this:

<script src="xregexp.js"></script>
<script src="addons/unicode-base.js"></script>
<script src="addons/unicode-categories.js"></script>

But trying the above just causes ReferenceError: exports is not defined.

How can I load XRegExp with only some of its addons?


Solution

  • The usage you show with script may have worked with earlier versions of XRegExp but it is now obsolete, and the new usage does not seem to be documented anywhere.

    You can load xregexp-all.js with a script tag because it has a UMD wrapper at the very beginning of the file which allows this usage. However, if you look at the transpiled addon files that are shipped with XRegExp, you'll see code like this in each addon:

    'use strict';
    
    Object.defineProperty(exports, "__esModule", {
        value: true
    });
    
    exports.default = function (XRegExp) {
    // ...
    };
    

    This tells you two things. One is that the addons are modules, period. They do not have UMD wrappers so loading them with script won't work. Secondly, the addons export one thing: a function. As the name of the argument suggests, you need to pass to it the XRegExp library itself so that the addon can install itself. A further clue is found in the src/index.js source in the repository. It contains:

    import XRegExp from './xregexp';
    
    import build from './addons/build';
    import matchRecursive from './addons/matchrecursive';
    import unicodeBase from './addons/unicode-base';
    import unicodeBlocks from './addons/unicode-blocks';
    import unicodeCategories from './addons/unicode-categories';
    import unicodeProperties from './addons/unicode-properties';
    import unicodeScripts from './addons/unicode-scripts';
    
    build(XRegExp);
    matchRecursive(XRegExp);
    unicodeBase(XRegExp);
    unicodeBlocks(XRegExp);
    unicodeCategories(XRegExp);
    unicodeProperties(XRegExp);
    unicodeScripts(XRegExp);
    
    export default XRegExp;
    

    After installing XRegExp with npm, this is what I use in a project of mine (which must run as-is on ES5 engines) where I want to load XRegExp with only some Unicode addons and nothing else:

    var XRegExp = require("xregexp/lib/xregexp");
    var base = require("xregexp/lib/addons/unicode-base");
    var blocks = require("xregexp/lib/addons/unicode-blocks");
    var categories = require("xregexp/lib/addons/unicode-categories");
    
    base(XRegExp);
    blocks(XRegExp);
    categories(XRegExp);
    

    This code works in Node and is also properly processed by Webpack for use in the browser.