'Nodejs: use import in only one file

I have a project which is build using require, but now I need to use a package @nfteyez/sol-rayz, which only have support for ES6 import.

I cannot add type: module because there are lots of files.

I have tried changing file to mjs, but I get errors when importing it with require in another file.

I found in example that is possible when you enable module you can use import with:

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

is there something similar for import? I am using node v17



Solution 1:[1]

in node.js v14 and above, we can enable es module support by just add this in package.json

"type": "module"

Solution 2:[2]

Go for dynamic import() function.

let solRayz = await import('@nfteyez/sol-rayz');

For complete suppression and use one common style, it is very difficult as the implicit packages have their own module system in their package files. For this particular problem, the following links might help

Complete flexibility of using module systems is not available as of now

What is the difference between .js and .mjs files?

https://nodejs.org/docs/latest/api/esm.html#esm_differences_between_es_modules_and_commonjs

https://www.geeksforgeeks.org/how-to-use-an-es6-import-in-node-js/

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 galih wisnuaji
Solution 2