Why "exports is not defined in ES module scope" on a new project?

Viewed 45

I would like to use cashify, but when try in on a new project, I get the below error.

tsc index.ts && node index.js

file:///home/ss/test/index.js:2
exports.__esModule = 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 '/home/ss/test/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at file:///home/ss/test/index.js:2:1

Using node -v v16.16.0 and tsc -v Version 4.7.4 and have set to target ES2021, as that seams to be the latest version Node 16.16 supports.

I have followed this howto, and made the changes accordingly.

Question

Can anyone figure out what I am doing wrong?

PoC repo here: git clone https://github.com/littlesandra88/p1

index.ts

import {convert} from 'cashify';
const rates = {
        GBP: 0.92,
        EUR: 1.00,
        USD: 1.12
};
const result = convert(10, {from: 'EUR', to: 'GBP', base: 'EUR', rates});
console.log(result); //=> 9.2

package.json

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "exports": "./index.js",
  "type": "module",
  "engines": {
    "node": ">=16.16.0"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cashify": "^3.0.1"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "module": "ES2021",
    "moduleResolution": "node16",
    "target": "ES2021",
    "lib": ["ES2021"],
    "allowJs": true,
    "outDir": "build",
    "rootDir": "src",
    "strict": true,
    "noImplicitAny": true,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "types": ["node"],
    "typeRoots": ["./node_modules/@types"]
  },
  "include": ["src/**/*"],
  "exclude": ["src/**/*.spec.ts"]
}
1 Answers

Cashify is an ESM module, which you can't mix with your ES2017 modules.

You can checkout my fork Cashify-es2017, which works with regular projects.

Related