Search code examples
javascriptreact-nativecommonjses6-modules

Is there a way to lazy export file with ESModule?


I have a project which has many files to export. For now I use CommonJS to lazy export those files:

module.exports = {
  get AccessibilityInfo() {
    return require('../Components/AccessibilityInfo/AccessibilityInfo');
  },
  get ActivityIndicator() {
    return require('../Components/ActivityIndicator/ActivityIndicator');
  },
  // .... many other files 
 }

ReactNative do the same thing React Native, so that a file is only loaded when it is imported specifically.

I want to refactor this file with ESModule, but I can't find a way to export files lazily.
Is there a way to export files lazily with ESModule?
Is it necessary to export files lazily with ESModule?


Solution

  • The ECMAScript way of doing this is via dynamic import(). The syntax is basically the same and it does what you'd expect, except that it returns a promise (which is great - it means that the operation does not lock the thread). Your code could e.g. look like this:

    export const getAccessibilityInfo = () =>
      import("../Components/AccessibilityInfo/AccessibilityInfo");
    
    export const getActivityIndicator = () =>
      import("../Components/ActivityIndicator/ActivityIndicator");
    

    You would then grab these modules like this:

    import { getActivityIndicator } from "./the/module/above";
    
    const ActivityIndicatorPromise = getActivityIndicator();
    
    // Whenever you need to use the ActivityIdicator module, you first need to await for the promise resolution
    
    ActivityIndicatorPromise.then(ActivityIndicatorModule => {
      // Do what you want here...
    });
    

    You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Imports. It also lists the cases where this syntax would be preferable. If you were hoping that this was possible using the static import syntax (import X from '../whatever';), rest assured - it is not.