'cannot use Lowdb 3 which is a pure ESM package in a typescript project

I'm using https://github.com/typicode/lowdb v 3 in my typescript projct.

package.json

{
  "name": "todo",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": {
    "inquirer": "^8.2.0",
    "lowdb": "^3.0.0"
  },
  "devDependencies": {
    "@types/inquirer": "^8.2.0"
  }
}

tsconfig.json

{
    "compilerOptions": {
        "target": "ES2020",
        "outDir": "./dist",
        "rootDir": "./src",
        "module": "CommonJS",
    }
}

I compile by tsc and execute by: node dist/index.js I get this error:

internal/modules/cjs/loader.js:1102
      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\Users\oo\Root\Dev\Playground\Typescript\todo\node_modules\lowdb\lib\index.js
require() of ES modules is not supported.
require() of C:\Users\oo\Root\Dev\Playground\Typescript\todo\node_modules\lowdb\lib\index.js from C:\Users\oo\Root\Dev\Playground\Typescript\todo\dist\jsonTodoCollection.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from C:\Users\oo\Root\Dev\Playground\Typescript\todo\node_modules\lowdb\package.json.

    at new NodeError (internal/errors.js:322:7)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1102:13)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:93:18)
    at Object.<anonymous> (C:\Users\oo\Root\Dev\Playground\Typescript\todo\dist\jsonTodoCollection.js:4:17)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32) {
  code: 'ERR_REQUIRE_ESM'

How Can I use this package in my typescript project. Thanks.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source