EverydayDeveloper
EverydayDeveloper

Reputation: 1150

Cannot use import statement outside modules

I am using NextJS with typescript, mongo Atlas, mongoose, node and express.

I am getting the following error when I run node pages/server: I have uploaded my package.json file and have added babel as well

import express from 'express'; ^^^^^^

SyntaxError: Cannot use import statement outside a module at wrapSafe (internal/modules/cjs/loader.js:1072:16) at Module._compile (internal/modules/cjs/loader.js:1122:27) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10) at Module.load (internal/modules/cjs/loader.js:1002:32) at Function.Module._load (internal/modules/cjs/loader.js:901:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12) at internal/main/run_main_module.js:18:47

This is my server.js code:

import express from 'express';
import { connect, connection } from 'mongoose';
import morgan from 'morgan';
import path from 'path';
const app = express();
const PORT = process.env.PORT || 8080;
//Success
   import routes from './routes/api.tsx';

const MONGODB_URI = 'xxx';

// const routes=require('./routes/api')
connect(MONGODB_URI ||'mongodb://localhost/success', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

connection.on('connected', () => {
    console.log('Mongoose is connected');
});

const newBlogPost = new BlogPost(data); //instance of the model

app.use(morgan('tiny'));
app.use('/',routes)

app.listen(PORT, console.log(`Server is starting at ${PORT}`));

package.json file

{
  "name": "la-sheild",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "babel-node server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/express": "^4.17.2",
    "@types/mongoose": "^5.7.1",
    "axios": "^0.19.2",
    "concurrently": "^5.1.0",
    "express": "^4.17.1",
    "mongoose": "^5.9.1",
    "morgan": "^1.9.1",
    "next": "^9.2.2",
    "node": "^13.8.0",
    "react": "^16.12.0",
    "react-dom": "^16.12.0"
  },
  "devDependencies": {
    "@babel/core": "^7.8.4",
    "@babel/preset-env": "^7.8.4",
    "@babel/register": "^7.8.3",
    "@types/node": "^13.7.4",
    "@types/react": "^16.9.21",
    "babel-cli": "^6.26.0",
    "typescript": "^3.7.5"
  },
  "proxy": "http://localhost:8080"
}

Upvotes: 23

Views: 116091

Answers (7)

Mohammad Alnusairat
Mohammad Alnusairat

Reputation: 1

Replace the import statement with the following line of code,

const MongoClient = require('mongodb').MongoClient;

Upvotes: -1

Romain TAILLANDIER
Romain TAILLANDIER

Reputation: 1995

I had my index.ts importing an exported var from my schema.js file.
I was doing an import inside this schema.js file
It was this second import causing the 'Cannot use import statement outside modules'.
Finally renaming the file from schema.js to schema.ts solved the issue.\

Upvotes: 0

javed iqbal
javed iqbal

Reputation: 67

I was getting same error "SyntaxError: Cannot use import statement outside a module" first i add tye : module but still face another error. Finaly its work for me the issue was this i was running my Driver.js file that why i was getting this issue. i run my Driver.ts file its work ok for me. enter image description here

But after run my with extenstion .ts file its work. enter image description here

Upvotes: 1

Yilmaz
Yilmaz

Reputation: 49293

Here is the solution based on ts-next-express.

 npm i --save ts-node

create another config file for express because node is using common.js module but if you check the tsconfig.json you will see this:"module": "esnext"

tsconfig.server.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "module": "commonjs",
    "outDir": "dist",
    "noEmit": false
  },
  "include": ["server"]
}

set the script as follow:

 "start": "ts-node --project tsconfig.server.json server.ts"

Upvotes: 1

Mekky_Mayata
Mekky_Mayata

Reputation: 317

The following solution worked for me;

  • install needed packages

    npm install nodemon @babel/core @babel/node @babel/preset-env -D

  • create a .babelrc file in the working directory and paste the following in it

    {
    "presets": [
    "@babel/preset-env" ]
    }
    
    
  • lastly, add the code below to "scripts" in package.json

    "dev": "nodemon —exec babel-node server.js" where server.js is your file in this case.

Hope this works :)

Upvotes: 12

Deep Kakkar
Deep Kakkar

Reputation: 6297

Since Node v12, you can use either the .mjs extension or set "type": "module" in your package.json.

And you need to run node with the --experimental-modules flag.

node --experimental-modules server.mjs

You can check the SO link

Or you can create .babelrc file in the root of your project. Add following (and any other babel presets you need, can be added in this file):

{
    "presets": ["env"]
}

Install babel-preset-env using

npm install babel-preset-env
npm install babel-cli -g

# OR

yarn add babel-preset-env
yarn global add babel-cli

Now, go to the folder where your server.js file exists and

run using:

babel-node fileName.js

Or you can run using npm start by adding following code to your package.json file:

"scripts": {
    "start": "babel-node server.js"
}

There is a tutorial link for Set Up Next.js with a Custom Express Server + Typescript on a medium that will be very helpful for you.

Upvotes: 16

Suhas Dhongade
Suhas Dhongade

Reputation: 79

"scripts": { "start": "babel-node server.js" }

adding above worked for me

Upvotes: -2

Related Questions