I am using TypeScript to build a Node.js application. After compiling the code, when I run the output JavaScript file using npm start
, it throws the following error:
When I run the following command:
npm start
I get this error:
SyntaxError: Cannot use import statement outside a module
My app.ts (mainfile):
import "reflect-metadata"
import express from 'express';
import dotenv from 'dotenv';
import { useExpressServer } from 'routing-controllers';
import { connectDB } from './config/db';
import { CONNECTED_MESSAGE } from './common';
import { ENV_DETAILS } from './env';
dotenv.config();
// Create an instance of an Express app
const app = express();
// Configure built-in middleware to parse various types of request bodies
app.use(express.json()); // For parsing application/json
app.use(express.urlencoded({ extended: true })); // For parsing application/x-www-form-urlencoded
// Configure routing-controllers with the Express app
useExpressServer(app, {
controllers: ENV_DETAILS.dirs.controllers
});
// Connect to the database and start the server
const port = 3000;
connectDB().then(() => {
app.listen(port, () => {
console.log(CONNECTED_MESSAGE.listenPort, `${port}`);
});
});
My package.json File:
"scripts": {
"test": "echo "Error: no test specified" && exit 1",
"start": "node dist/app.js",
"dev": "tsx src/app.ts",
"build": "tsc && tsc-alias"
},
My tsconfig.json File:
{
"compilerOptions": {
"module": "ESNext",
"target": "ESNext",
"moduleResolution": "node",
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"resolveJsonModule": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"baseUrl": ".",
"paths": {
"@src/*": [
"src/*"
]
}
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules",
"dist"
]
}
Environment : Node.js version: 20.12.2 and npm version: 6.14.11
I expect the command npm start
to execute the compiled code without throwing an error.
Are there any issues with my configuration, or am I missing something critical?
How can I resolve this Error?