Oliver Kucharzewski
Oliver Kucharzewski

Reputation: 2645

Issues compiling nodejs code with ts-node (Cannot use import statement outside a module)

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.

Upvotes: 0

Views: 343

Answers (1)

Seth Lutske
Seth Lutske

Reputation: 10686

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

Upvotes: 2

Related Questions