Home > other >  How can i use requier and import statments in node js , at the same file
How can i use requier and import statments in node js , at the same file

Time:12-06

my problem when i was working on my node js file , is that im importing readline statments , and using ( 'type': 'module' ) at the same time , wanting to use both ways while no errors how can i use requier on ( readline ) command ?
the type of error im facing is :

SyntaxError: Cannot use import statement outside a module

i tried to use module on ( packag.json) but then the requier statment will face type error i couldnt ( transfare) (import readline, { clearScreenDown } from "readline"; ) as an a requier statement like this (const db = require('./dbConnection');)

CodePudding user response:

You can't, they're mutually-exclusive. import is ESM (JavaScript's native, specified module system), and require is CommonJS (Node.js's older module system).

Instead, you have to use ESM or CommonJS consistently.

If you need to do a dynamic (runtime-determined) import in ESM, you can use the import() pseudo-function, which is a bit like CommonJS require except that rather than making the calling code wait, it returns a promise.

CodePudding user response:

Answer depends on the choice of method you want to use.

  1. Use import ABC from 'ABC' (node core module or packages downloaded via npm)
  2. User const abc = require('./ABC') for your custom modules. below are examples.

ABC.js

const ABC = ()=> {
 return "ABC is called";
}
module.exports=ABC;

now in file you want to call it. index.js

const abc = require('./ABC');
  • Related