kanulilewa
kanulilewa

Reputation: 35

type: module is causing: SyntaxError: Cannot use import statement outside a module

I've researched this error - apparently should be fixed by adding "type": "module" to the package.json or renaming js files to .mjs - nothing works. Please help! I've been trying to figure out why it is causing this error: import app from './server.js'; SyntaxError: Cannot use import statement outside a module Also, all the files are located in the same folder so there shouldn't be any scope issues.

Index.js

import app from './server.js';
import mongodb from "mongodb";
import dotenv from "dotenv";

async function main(){
    
    dotenv.config();

    const client = new mongodb.MongoClient(
        preocess.env.MOVIEREVIEWS_DB_URI
    );

    const port = process.env.PORT || 8000;

    try {
        await client.connect()
        app.listen(port, () => {
            console.log('server is running on port: ' + port);
        });
    }catch(e){
        console.error(e);
        process.exit(1)
    }
}
main().catch(console.error);

server.js

import express from 'express';
import cors from 'cors';
import movies from './api/movies.route.js';

const app = express();

app.use(cors());
app.use(express.json());

app.use("api/v1/movies", movies);
app.use("*", (req, res) => {
    res.status(404).json({error: "not found"});
});

export default app;

package.json

{
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^16.0.3",
    "express": "^4.18.1",
    "mongodb": "^4.10.0"
  }
}

Upvotes: 1

Views: 1486

Answers (1)

Neeraj Kumar
Neeraj Kumar

Reputation: 418

I think the problem lies in the way you're importing dotenv. See here How to import dotenv using ES6 and try using it like this.

import * as dotenv from 'dotenv'

Upvotes: 1

Related Questions