'How can i do npm module support import and require?

I uploaded my first module to npm in Javascript and I want it to support import and require. Is this possible?

The module is this: https://www.npmjs.com/package/@dariodigulio/pro-log-js



Solution 1:[1]

Yes, I get the same error when I did try to require() your package. But, then I manged to get both working (import...from and require()) by converting your package code to commonjs compatible.

You should try to publish the package as commonjs (require()) module and then you'll get support from Node to choose either syntax on application side.

I did following change in your code to get both syntax working.

  1. Removed the "type": "module" from package.json.
  2. Update the main entry from "main": "ProLog.mjs", to "main": "ProLog.js".
  3. Replace the import...from syntax with require() in ProLog.js file.
  4. Update the export class ProLog to module.exports = ProLog.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Viral Patel