• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# import-lazy [![Build Status](https://travis-ci.org/sindresorhus/import-lazy.svg?branch=master)](https://travis-ci.org/sindresorhus/import-lazy)
2
3> Import modules lazily
4
5
6## Install
7
8```
9$ npm install --save import-lazy
10```
11
12
13## Usage
14
15```js
16// Pass in `require` or a custom import function
17const importLazy = require('import-lazy')(require);
18const _ = importLazy('lodash');
19
20// Where you would normally do
21_.isNumber(2);
22
23// You now instead call it as a function
24_().isNumber(2);
25
26// It's cached on consecutive calls
27_().isString('unicorn');
28
29// Extract lazy variations of the props you need
30const members = importLazy('lodash')('isNumber', 'isString');
31
32// Useful when using destructuring assignment in ES2015
33const {isNumber, isString} = importLazy('lodash')('isNumber', 'isString');
34
35// Works out of the box for functions and regular properties
36const stuff = importLazy('./math-lib')('sum', 'PHI');
37console.log(stuff.sum(1, 2)); // => 3
38console.log(stuff.PHI); // => 1.618033
39```
40
41### Proxy support in Node.js 6 or later
42
43If you use Node.js 6 or later, you can take advantage of ES2015 proxies and don't need to call it as a function.
44
45```js
46const importLazy = require('import-lazy').proxy(require);
47const _ = importLazy('lodash');
48
49// No need to call it as a function but still lazily imported
50_.isNumber(2);
51```
52
53## Related
54
55- [resolve-from](https://github.com/sindresorhus/resolve-from) - Resolve the path of a module from a given path
56- [import-from](https://github.com/sindresorhus/import-from) - Import a module from a given path
57- [resolve-pkg](https://github.com/sindresorhus/resolve-pkg) - Resolve the path of a package regardless of it having an entry point
58- [lazy-value](https://github.com/sindresorhus/lazy-value) - Create a lazily evaluated value
59- [define-lazy-prop](https://github.com/sindresorhus/define-lazy-prop) - Define a lazily evaluated property on an object
60
61
62## License
63
64MIT © [Sindre Sorhus](https://sindresorhus.com)
65