ES6 import error handling

Supplementary dynamic import.

class ImportError extends Error {}

const loadModule = async (modulePath) => {
  try {
    return await import(modulePath)
  } catch (e) {
    throw new ImportError(`Unable to import module ${modulePath}`)
  }
}

async function main() {
  // import myDefault, {foo, bar} from '/modules/my-module.js'
  const { default: myDefault, foo, bar } = await loadModule('/modules/my-module.js')
}

or chained_promises

import("/modules/my-module.js").then(module=>{
  module.foo()
  module.bar()
}).catch(err=>
  console.log(err.message)
)

or Destructuring assignment

import("/modules/my-module.js").then(({foo, bar})=>{
  foo()
  bar()
}).catch(err=>
  console.log(err.message)
)

You can't catch static imports errors (cf. Boris' answer)

Yet, you could use a dynamic import() for that.

It's now supported by all evergreen browsers & Node, and is part of the standards since ES2020.

class ImportError extends Error {}

const loadModule = async (modulePath) => {
  try {
    return await import(modulePath)
  } catch (e) {
    throw new ImportError(`Unable to import module ${modulePath}`)
  }
}

[2021 Edit] Look at Caveman answer for a more up to date answer allowing to make dynamic import

This talk give it away : https://github.com/ModuleLoader/es-module-loader/issues/280 and agree with what you said.

import only works at the base level. They are static and always load before the module is run.

So you can't do a code check.

But, the good news is that as it's static, it can be analysed, tools like webpack throw errors at build time.

Tags:

Node.Js