Import a module lazily
Switch branches/tags
Clone or download
jamestalmage and sindresorhus fix(documentation): Destructuring the import will cause eager fetchin…
…g. (#12)

The current documentation suggests you can use object destructuring for lazy imports, but doing so triggers the import immediately, creating an eager import.

Includes a test to prove it.
Latest commit 4b06b4a Dec 10, 2017

import-lazy Build Status

Import a module lazily

Note: Version 3 is exclusively Proxy-based and requires Node.js 6+. Use version 2 if you need Node.js <=5 support.


$ npm install import-lazy


// Pass in `require` or a custom import function
const importLazy = require('import-lazy')(require);
const _ = importLazy('lodash');

// Instead of referring to its exported properties directly…

// …it's cached on consecutive calls

// Works out of the box for functions and regular properties
const stuff = importLazy('./math-lib');
console.log(stuff.sum(1, 2)); // => 3
console.log(stuff.PHI); // => 1.618033

Warning: Destructuring will make cause it to fetch eagerly

While you may be tempted to do leverage destructuring, like this:

const {isNumber, isString} = importLazy('lodash');

Note that this will cause immediate property access, negating the lazy loading, and is equivalent to:

import {isNumber, isString} from 'lodash';


  • resolve-from - Resolve the path of a module from a given path
  • import-from - Import a module from a given path
  • resolve-pkg - Resolve the path of a package regardless of it having an entry point
  • lazy-value - Create a lazily evaluated value
  • define-lazy-prop - Define a lazily evaluated property on an object


MIT © Sindre Sorhus