Security News
Bun 1.2 Released with 90% Node.js Compatibility and Built-in S3 Object Support
Bun 1.2 enhances its JavaScript runtime with 90% Node.js compatibility, built-in S3 and Postgres support, HTML Imports, and faster, cloud-first performance.
lazy-cache
Advanced tools
The lazy-cache npm package is designed to lazily require modules, meaning that the modules are only required when they are actually needed. This can help improve the performance of your application by deferring the loading of modules until they are used.
Lazy Loading of Modules
This feature allows you to defer the loading of a module until it is actually used in your code. In the example, the 'fs' module is not loaded until the 'readFileSync' method is called.
const lazy = require('lazy-cache')(require);
const fs = lazy('fs');
// fs is not loaded until it is used
fs.readFileSync('path/to/file.txt', 'utf8');
Custom Lazy Loading
You can also use lazy-cache to lazily load your own custom modules. In this example, the './customModule' is not loaded until 'someFunction' is called.
const lazy = require('lazy-cache')(require);
const customModule = lazy('./customModule');
// customModule is not loaded until it is used
customModule.someFunction();
The require-lazy package provides similar functionality by allowing you to lazily require modules. It offers a simple API for deferring the loading of modules until they are needed, similar to lazy-cache.
Proxyquire is a powerful tool for mocking dependencies during testing, but it also supports lazy loading of modules. It allows you to mock out dependencies and control when they are loaded, providing more flexibility compared to lazy-cache.
Import-lazy is another package that allows you to lazily import modules. It uses ES6 proxies to defer the loading of modules until they are accessed, offering a modern alternative to lazy-cache.
Cache requires to be lazy-loaded when needed.
Install with npm:
$ npm install --save lazy-cache
It's suprising how many libraries are in the average dependency tree that don't belong there for one reason or another. Either because they were accidentally listed as dependencies
instead of devDepedencies
, or they are required in a file as variables, but the variable is never actually used (poor linting), and so on. Or because the maintainer made the decision to add the deps, even though they will never (or can't ever) be used by 99.9% of users.
Worse, many libraries like chalk and shelljs actually execute code when require()
is called!? (shelljs was modifying the String.prototype
, and chalk loops over some objects to dynamically create methods). In other words, they do something like this:
// in the main export of a library, if you do this it will
// automatically modify the String.prototype _globally_,
// the moment node.js loads the dependency tree
String.prototype.foo = function() {};
// same if you do something like this
// (dont' do this, ever. wrap this kind of code in a function
// and allow implementors to decide when to call it)
while (foo) {
// do stuff
}
In any case, just having these libraries in your dependency tree somewhere means that their code will excecute the moment you run your application even if the libraries are never called by your application or any other code anywhere in the tree.
solution
lazy-cache doesn't use any "magic", it uses native, plain-vanilla, tried and true javascript getters to call node's require()
system.
Faster, safer code
There main advantage to this, the main is that require
s are loaded on demand, so only code that is actually used will ever be loaded. As a result, applications will load faster (sometimes much faster - we've seen load times drop from ~1 second to less than 50 milliseconds).
Moreover, in some cases this also avoids inadvertently loading libraries that execute code or modifies globals, etc.
webpack users
If you use webpack and are experiencing issues with lazy-cache, this is a known bug caused by webpack, not lazy-cache. There is a solution though, you can use unlazy-loader, a webpack loader that fixes the webpack bug.
var utils = require('lazy-cache')(require);
Use as a property on lazy
The module is also added as a property to the lazy
function so it can be called without having to call a function first.
var utils = require('lazy-cache')(require);
// `npm install glob`
utils('glob');
// glob sync
console.log(utils.glob.sync('*.js'));
// glob async
utils.glob('*.js', function (err, files) {
console.log(files);
});
Use as a function
var utils = require('lazy-cache')(require);
var glob = utils('glob');
// `glob` is a now a function that may be called when needed
glob().sync('foo/*.js');
An alias may be passed as the second argument if you don't want to use the automatically camel-cased variable name.
Example
var utils = require('lazy-cache')(require);
// alias `ansi-yellow` as `yellow`
utils('ansi-yellow', 'yellow');
console.log(utils.yellow('foo'));
Dot notation may also be used in the alias to create an object hierarchy.
Example
var utils = require('lazy-cache')(require);
utils('ansi-cyan', 'color.cyan');
utils('ansi-yellow', 'color.yellow');
utils('ansi-magenta', 'color.magenta');
console.log(utils.color.cyan('foo'));
console.log(utils.color.yellow('bar'));
console.log(utils.color.magenta('baz'));
Example
var utils = require('lazy-cache')(require);
// temporarily re-assign `require` to trick browserify
var fn = require;
require = utils;
// list module dependencies (here, `require` is actually `lazy-cache`)
require('glob');
require = fn; // restore the native `require` function
/**
* Now you can use glob with the `utils.glob` variable
*/
// sync
console.log(utils.glob.sync('*.js'));
// async
utils.glob('*.js', function (err, files) {
console.log(files.join('\n'));
});
To force lazy-cache to immediately invoke all dependencies, do:
process.env.UNLAZY = true;
lint-deps: CLI tool that tells you when dependencies are missing from package.json and offers you a… more | homepage
Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.
Commits | Contributor |
---|---|
31 | jonschlinkert |
27 | doowb |
(This document was generated by verb-generate-readme (a verb generator), please don't edit the readme directly. Any changes to the readme must be made in .verb.md.)
To generate the readme and API documentation with verb:
$ npm install -g verb verb-generate-readme && verb
Install dev dependencies:
$ npm install -d && npm test
Jon Schlinkert
Copyright © 2016, Jon Schlinkert. Released under the MIT license.
This file was generated by verb-generate-readme, v0.2.0, on November 07, 2016.
FAQs
Cache requires to be lazy-loaded when needed.
The npm package lazy-cache receives a total of 3,891,469 weekly downloads. As such, lazy-cache popularity was classified as popular.
We found that lazy-cache demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Bun 1.2 enhances its JavaScript runtime with 90% Node.js compatibility, built-in S3 and Postgres support, HTML Imports, and faster, cloud-first performance.
Security News
Biden's executive order pushes for AI-driven cybersecurity, software supply chain transparency, and stronger protections for federal and open source systems.
Security News
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.