4

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
  • 83
  • 335
  • 359
Klathmon
  • 265
  • 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

1 Answers1

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,548
  • 1
  • 23
  • 38