Home

Awesome

import-lazy

Import a module lazily

Install

$ npm install import-lazy

Usage

// 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…
_.isNumber(2);

// …it's cached on consecutive calls
_.isNumber('unicorn');

// 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

Note

Destructuring will 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';

Usage with bundlers

If you're using a bundler, like Webpack, you'll have to import your modules like this in order to have them properly bundled:

const importLazy = require('import-lazy');

const _ = importLazy(() => require('lodash'))();

Related


<div align="center"> <b> <a href="https://tidelift.com/subscription/pkg/npm-import-lazy?utm_source=npm-import-lazy&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a> </b> <br> <sub> Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies. </sub> </div>