15
votes

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"
}
5
have you installed express? i.e. Is express exists in package.json file?Deep Kakkar
Yes, it does: "dependencies": { "@types/express": "^4.17.2", "@types/mongoose": "^5.7.1", "axios": "^0.19.2", "concurrently": "^5.1.0", "express": "^4.17.1", @DeepKakkarEverydayDeveloper
Have you Enabled ES6 Imports?Deep Kakkar
Can you please share your package.json file?Deep Kakkar

5 Answers

10
votes

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.

10
votes

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 :)

1
votes

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"
1
votes

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

-1
votes

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

adding above worked for me