linex
linex

Reputation: 33

Azure Functions: Cannot use import statement outside a module

I couldn't find a recent question talking about this so I decided to create a new one.

I'm building some azure functions with Typescript and I'm getting:

import { Entity, BaseEntity, PrimaryColumn, Column, ManyToOne } from "typeorm"; SyntaxError: Cannot use import statement outside a module

This is my tsconfig

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "outDir": "dist",
    "rootDir": ".",
    "sourceMap": true,
    "esModuleInterop": true,
    "strict": true,
    "lib": [
      "esnext"
    ],
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "moduleResolution": "Node",
    "allowSyntheticDefaultImports": true
  }
}

Any ideas how to solve this? Thanks!

Upvotes: 2

Views: 2837

Answers (2)

Jurijs Kovzels
Jurijs Kovzels

Reputation: 6240

There are 2 places to check and align:

  1. tsconfig.json
  2. package.json

tsconfig.json controls what Typescript compiler emits and how it resolves modules compilation-time. Important options in tsconfig are:

package.json, in turn, controls how Nodejs resolves modules at run-time. Important option is type. Of omitted commonjs is implied.

You want both to be aligned.

If you want classic go for:

//in package.json
"type": "commonjs",

//in tsconfig.json
"module": "CommonJS",
"moduleResolution": "node",

If you want futuristic, more readable, and backward-compatible to CommonJs output, use the following for ES modules:

//in package.json
"type": "module",

//in tsconfig.json
"module": "NodeNext",
"moduleResolution": "nodenext",

Upvotes: 0

SaiSakethGuduru
SaiSakethGuduru

Reputation: 2440

Here are the 2 fixes you need to do to resolve the syntax error

  1. Change .js files to .cjs
  2. Also add "type" : "Module" to package.json

Also check the related SO threads and Documentation.

Upvotes: 2

Related Questions