5

Is there a way using ES2015 (using the import syntax) to import a module only if it exists?

For example, I want to use a natively-compiled module if it can be installed, but fallback to a pure-js module if it fails for any reason.

I had assumed the following would work:

let crc32;
try {
  import Sse4Crc32 from 'sse4_crc32';
  crc32 = Sse4Crc32.calculate;
} catch (e) {
  import crcJs from 'crc';
  crc32 = crcJs;
}

However it gives the error 'import' and 'export' may only appear at the top level. Is there a way to do this using the import syntax in ES2015?

Jeremy
  • 1
  • 85
  • 340
  • 366
Klathmon
  • 273
  • 1
  • 11
  • See also [*How can I conditionally import an ES6 module?*](https://stackoverflow.com/questions/36367532/how-can-i-conditionally-import-an-es6-module). – Franklin Yu Nov 29 '18 at 20:27

2 Answers2

3

That is not possible in ES2015, imports only work at the top level. Since you're using node I would use require instead in this case.

glued
  • 2,579
  • 1
  • 25
  • 40
1

This is beyond old, but if anyone wants to do this nowadays it is possible through dynamic imports.

(async () => {
  try {
    const a = await import("this does not exist");
  } catch {
    console.log("Caught");
  }
})();
fmcc091
  • 36
  • 2
  • 3