1

I have a NodeJS app with a lot of routes, functions, etc. I have a lot of files with const xxx = require('yyy'). I now want to use this: https://www.npmjs.com/package/simple-ldap-search I thought my journey would be as peaceful as it has been for now, but I can't use it, let me explain: instead of the usual require, I have to use import, as described in the documentation:

import SimpleLDAP from 'simple-ldap-search';

I searched on StackOverflow, and I saw I could put "type": "module" in the top package.json file, but then if I do I can't use require... It seems unsolvable.

Does it mean I have to choose between using ES6 or CommonJS? I read this question: Using Node.js require vs. ES6 import/export

  1. I have the impression the import is more efficient, am I right?
  2. Is it possible to use simple-ldap-search in my current node app without making big changes?
  3. Is it possible to "convert" (I know it's not the precise term but I think you'll understand) the use of require to import and vice-versa?

Thanks for your answers.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
djcaesar9114
  • 1,880
  • 1
  • 21
  • 41

3 Answers3

1

As this project issue states, it isn't possible to use require in a project that switched to type: "module" in its package.json. For these use cases one would need to use a loader like Babel, etc.

It is worth considering switching over to ES modules, i.e to add type: "module" to your top-level package.json. It is still possible to import a CommonJS module with import but it does not work the other way around.

Alternatively, you can switch back to a 2.x version of that package, from what I see they made the switch to ES modules from 3.0.0 onwards.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Attila
  • 91
  • 1
  • 6
0

While you can't use import in a commonjs file, you can use import()

This will make it more annoying when having to deal with the async loading, but is probably easier than converting your entire project to ESModules.

const simpleLDAPLoader = import('simple-ldap-search');
// later

async function () {
  const {default: SimpleLDAP} = await simpleLDAPLoader;

  const simpleLDAP = new SimpleLDAP();

}

Adn this will use the cached version every time you await the exisiting promise

Source: https://nodejs.org/api/esm.html#esm_interoperability_with_commonjs

Using require to load an ES module is not supported because ES modules have asynchronous execution. Instead, use import() to load an ES module from a CommonJS module.

coagmano
  • 5,542
  • 1
  • 28
  • 41
0

I am not sure if it is going to help you in your case but I have found this solution for myself and I can use ES6 import and "require" at the same time. In package.json:

"type": "module"

And in your file:

import { createRequire } from "module";
const require = createRequire(import.meta.url);

Works for my projects!

Oxi_Bo
  • 31
  • 6