Cannot use import statement outside modules

EverydayDeveloper picture EverydayDeveloper · Feb 25, 2020 · Viewed 32.1k times · Source

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"
}

Answer

Deep Kakkar picture Deep Kakkar · Feb 25, 2020

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.