How to write a module that works with Node.js, RequireJS as well as without them

前端 未结 3 1192
故里飘歌
故里飘歌 2021-02-14 18:09

I am working on a JavaScript library for JSON/XML processing. My library works in browser as well as Node.js (with xmldom and xmlhttprequest modules).<

3条回答
  •  -上瘾入骨i
    2021-02-14 18:29

    This is what I ended up with:

    // If the require function exists ...
    if (typeof require === 'function') {
        // ... but the define function does not exists
        if (typeof define !== 'function') {
            // Assume we're in the Node.js environment
            // In this case, load the define function via amdefine
            var define = require('amdefine')(module);
            // Use xmldom and xmlhttprequests as dependencies
            define(["xmldom", "xmlhttprequest", "fs"], _jsonix_factory);
        }
        else {
            // Otherwise assume we're in the browser/RequireJS environment
            // Load the module without xmldom and xmlhttprequests dependencies
            define([], _jsonix_factory);
        }
    }
    // If the require function does not exists, we're not in Node.js and therefore in browser environment
    else
    {
        // Just call the factory and set Jsonix as global.
        var Jsonix = _jsonix_factory().Jsonix;
    }
    

提交回复
热议问题