soumyadeep.eth
soumyadeep.eth

Reputation: 11

I'm trying to compile my ts file in esm, but it is getting compiled as cjs

My setup: ts.config setup

{
  "compilerOptions": {
    "target": "es2016",
    "module": "NodeNext",
    "rootDir": "./src",
    "moduleResolution": "nodenext",
    "outDir": "./dist",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "skipLibCheck": true
  }
}

package.json

{
 "type": "module"
}

still after compiling to js when running node ./file.js command getting this error.

    Object.defineProperty(exports, "__esModule", { value: true });
                      ^
ReferenceError: exports is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and 'C:\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

what's the reason? what's the fix?

Upvotes: 0

Views: 64

Answers (1)

kayahr
kayahr

Reputation: 22050

tsc --help tells you right at the beginning:

  tsc app.ts util.ts
  Ignoring tsconfig.json, compiles the specified files with default compiler options.

So when you can call tsc ./filename.ts then the tsconfig is ignored and TypeScript uses its default options which means (unfortunately) CommonJS output.

Your options:

  1. If you don't want to use your tsconfig.json then add the -m or --module parameter:

    tsc -m nodenext ./filename.ts
    
  2. Put your source code into the src folder because that's configured in your tsconfig.json and then just run tsc. This actually uses your config, produces ESM output and places it into the dist folder as configured in your config.

Oh, and make sure your config is named tsconfig.json and not ts.config as mentioned in your question.

Upvotes: 0

Related Questions