Fuzzyma Fuzzyma - 6 months ago 30
Javascript Question

ES6 Modules, stop execution of code

It sounds like an odd question: How can I leave the execution context from an ES6 module?

See the following example:
Module1 requires some features in the browser to be present (say some new stuff not every Browser implements currentl).

You want to do a check in the module, if the required feature is available and if not, you want to stop the execution.

When writing that with an immediate function call, you can just call

return
and the following code is never executed.

How to do that in an ES6 module? Do I have to wrap the whole code into an
if
block?

Answer

If you export executable code from an ES6 module, you usually do so as a function:

export function myFunction() {
    ...
}

---

import { myFunction } from './module';
myFunction();

This function works just like any other that you define directly in the calling module. You can simply return to the caller as you would otherwise:

export function myFunction() {
    if(...) return;

    ...
}