Search code examples
javascriptmodulees6-modulescommonjsua-parser

Why can I use import statements in libraries that only support CommonJS modules?


Ua-parser-js only supports the CommonJS module. And when exporting, the export statement is not found:

    if (typeof(exports) !== UNDEF_TYPE) {
        // nodejs env
        if (typeof module !== UNDEF_TYPE && module.exports) {
            exports = module.exports = UAParser;
        }
        exports.UAParser = UAParser;
    } else {
        // requirejs env (optional)
        if (typeof(define) === FUNC_TYPE && define.amd) {
            define(function () {
                return UAParser;
            });
        } else if (typeof window !== UNDEF_TYPE) {
            // browser env
            window.UAParser = UAParser;
        }
    }

Nevertheless, why can I import UAParser by import { UAParser } from 'ua-parser-js'? This code was shown in the following SO answer and GitHub issue.

https://stackoverflow.com/a/57171046

https://github.com/faisalman/ua-parser-js/issues/423


Solution

  • There are two ways how this might work:

    • Your toolchain does transpile the import { UAParser } from 'ua-parser-js' statement into the legacy const { UAParser } = require('ua-parser-js');, which is then executed by node
    • Node ESM do support importing CommonJS modules for compatibility. The module.exports = UAParser; will be available as the default import, the exports.UAParser = UAParser; will be available the a named import you're doing.