Narayan Patel
Narayan Patel

Reputation: 113

Facing problem on importing express from express

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')
});

Upvotes: 8

Views: 32155

Answers (7)

vipul suryavanshi
vipul suryavanshi

Reputation: 104

Add "type": "module" to your package.json file.

{
  "name": "app-name",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  ......... 
}

strong text

Upvotes: -1

Harsha Bayyaram
Harsha Bayyaram

Reputation: 1

Add "type":"module" inside your package.json

{
  "name": "server",
  "version": "1.0.0",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon index.js"
  },
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "express": "^4.19.2"
  },
  "devDependencies": {
    "nodemon": "^3.1.4"
  }
}

Upvotes: 0

alinton gutierrez
alinton gutierrez

Reputation: 650

i always had used babel, with babel you can use both import and require in my case the error appears because use import and require. my solutions is:

step 1: install babel. you should run this command: `

npm i -D @babel/cli @babel/core @babel/node @babel/preset-env

`

step 2:say to babel that execute app.js or index.js. in file package.json in section "scripts" add this follow lines:

"devbabel": "nodemon app.js --exec babel-node",
"start": "babel-node app.js --exec"

step 3: create new file of type babel with name ".babelrc" with follow content:

{ "presets": ["@babel/preset-env"] }

done. its working for me in version 20 node.

Upvotes: -1

Juan David Arce
Juan David Arce

Reputation: 902

Use namespace import

import * as express from "express";

Upvotes: 5

alex
alex

Reputation: 33

add such line in your package.json:

"type": "module"

Upvotes: 1

Harshit Patel
Harshit Patel

Reputation: 11

Either you can use:

const express = require('express');

or just write:

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

Upvotes: 1

remy-actual
remy-actual

Reputation: 824

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

Upvotes: 15

Related Questions