0

When attempting to compile typescript code with NodeJS using the following command:

npx ts-node src/server.ts

I receive the following error:

SyntaxError: Cannot use import statement outside a module

I followed the instructions suggested by the error:

Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.

But upon following these, I still had no luck and another error was thrown instead.

Here is the content of my server.ts file.

import App from './app';
const app = new App();
app.listen(3080);

tsconfig.json contents:

{
  "compileOnSave": false,
  "compilerOptions": {
    "target": "ES2017",
    "lib": ["es2017"],
    "typeRoots": ["node_modules/@types"],
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "forceConsistentCasingInFileNames": true,
    "module": "commonjs",
    "pretty": true,
    "sourceMap": true,
    "declaration": true,
    "outDir": "./dist",
    "allowJs": true,
    "noEmit": false,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "importHelpers": true,
    "baseUrl": "src",
    "skipLibCheck": true,
    "paths": {
      "@/*": ["*"],
    }
  },
  "include": ["src/**/*.ts", "src/**/*.json", ".env"],
  "exclude": ["node_modules"]
}

I'm not really sure what is causing this but would greatly appreciate some wisdom on the issue.

Ideally i'd like to load the app via the server.ts file, while maintaining TypeScript contents.

1 Answer 1

2

You may need "moduleResolution": "node" in the compilerOptions for ts to recognize these types of imports.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.