Importing ES6 modules in CommonJS Node app?

Viewed 973

Long story short, I am trying to use an npm package that only has an ES6 module entrypoint, namely the bids-validator (GitHub), in a CommonJS module as my entire 50+ module app is built in CommonJS. According to the Node documentation, the standard way to do this is using the import() function. I tried this approach, with the following code:

async function importValidator() {
  const { validate } = await import('bids-validator')
  return validate
}

const validate = importValidator()

However, this results in an error from the bids-validator package, not necessarily the import function above:

error: unhandledRejection: Cannot use import statement outside a module
/*/app/api/node_modules/bids-validator/index.js:2
import validate from './validators'

Is there a way to circumvent this, so that I could use the package within a CommonJS module?

1 Answers

check that in the package.json what have you selected as the option. Make sure to select type:"common.js" instead of "module"

Related