Search code examples
node.jsnpmimportexportrequire

Is there a way to import from this node module with 'import' instead of 'require'?


I'm using this node module 'deep-equal' () and so far the only way I've been able to access the function in it is with var equal = require('deep-equal');, as suggested in the documentation. I usually use import instead of require, and am wondering if it's possible to use import with this module. The main function is exported from the file in this line:

var deepEqual = module.exports = function (actual, expected, opts) {...}

Is it possible to import this function with import, or is it only possible with require?

Thanks!


Solution

  • Yes you actually can.

    If you're using nodejs LTS then you'll have to use .mjs extension for the file where you're using import and pass experimental-modules flag while running node process.

    // foo.mjs
    import equal from 'deep-equal';
    
    node --experimental-modules foo.mjs
    

    As of nodejs 12.3.0 you can simply pass the experimental-modules. From docs

    Once enabled, Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code

    Also you can specify type as module in your package.json:

    // package.json
    {
      "type": "module"
    }
    
    

    From docs

    Files ending with .js or .mjs, or lacking any extension, will be loaded as ES modules when the nearest parent package.json file contains a top-level field "type" with a value of "module"