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

Time:11-22

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.

CodePudding user response:

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

CodePudding user response:

Seth's answer was 100%. Though turns out React was replacing the Typescript config with its own. I've extended it and modified the extension to replace React's configuration.

  • Related