2

I am working on MERN app and while importing express it is showing error it shows SyntaxError: Cannot use import statement outside a module my code is

import express from 'express';

const app = express();
const port = process.env.PORT || 3000;

app.get('/',(req,res)=>{
    res.send('this is homepage')
})

app.listen( port ,()=>{
    console.log('server is running at port number 3000')
});
Narayan Patel
  • 53
  • 1
  • 1
  • 6
  • 1
    is it this https://stackoverflow.com/questions/58211880/uncaught-syntaxerror-cannot-use-import-statement-outside-a-module-when-import – cmgchess May 17 '22 at 12:14
  • Replace `import express from 'express';` with `const express = require('express');` –  May 17 '22 at 12:15
  • 1
    Node with the extension `.js` will use common.js loader, eg. `require`, if you want to use ES loader, you can rename the file extension to `.mjs`. There are other subtle differences between ES & CommonJS, so you might want check those out.. eg, with ES you won't get the very useful `__dirname`, but there are workarounds for this. – Keith May 17 '22 at 12:22

5 Answers5

7

import and export are ES6 syntax.
To enable ES6 modules in your NodeJS app add "type": "module" to your package.json file.
Alternatively you can use the .mjs extension for your files.
Otherwise node defaults to the CommonJS module loader which uses require and module.exports syntax.

ES6 module support is stable in Node v12 and above, and in experimental in v9 - v11, requiring passing the --experimental-module flag.

Node.js documentation: Modules: ECMAScript modules

remy-actual
  • 724
  • 7
  • 19
2

Use namespace import

import * as express from "express";
Juan David Arce
  • 814
  • 8
  • 14
0

This works:

const e = require('express')
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Kwame Saka
  • 19
  • 3
0

Either you can use:

const express = require('express');

or just write:

"type": "module", in your package.json

Wyck
  • 10,311
  • 6
  • 39
  • 60
0

add such line in your package.json:

"type": "module"
alex
  • 23
  • 5
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 23 '23 at 11:20