select the commonjs file when running under commonjs of a dependency when running nodemon

Viewed 177

I am running node 14.

I have a package that has this in the package.json

  "main": "dist/index.js",
  "type": "commonjs",

There are no browser or module fields.

It is a typescript project that I compile to a .cjs output.

The problem is that when I start nodemon like this:

nodemon --watch 'src/**/*' -e ts,tsx --exec ts-node ./src/index.ts

I get this error:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /Users/blah/dist/index.js

The module in question has module, 'mainandbrowserfields but its type ismodule`.

It has index.js and index.cjs files but index.js file is being chosen.

everything is fine when I run the compiled output that which is a .cjs file.

Is there a way to let node know that I want everything to run under commonjs.

2 Answers

I don't think there is a way to have node do what you want. I had a similar where the main project was commonjs but one of the libraries was esm or a library it was using was esm. I don't remember the specific details but it was a royal pain.

The basic work around is to use esm to import the library giving you issue. It likely that once you do that you will end up with a second layer of issues.

// example
const esmImport = require('esm')(module)
const {CookieJar, fetch} = esmImport('node-fetch-cookies')

Dynamic import also resolved the issue for me.

async init() {
        const { CookieJar } = await import('node-fetch-cookies')
        this.cookieJar = new CookieJar()
        this.cookieJar.addCookie(`username=${this._user}`, this._url.toString())
        this.cookieJar.addCookie('hippa=yes', this._url.toString())
    }

I had the same issue and I used single quotation for multi-value args like `--exec' to solve it.

nodemon --watch 'src/**/*' -e ts,tsx --exec 'ts-node ./src/index.ts'
Related