Giter Site home page Giter Site logo

import-lazy's Introduction

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

  • 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

Get professional support for this package with a Tidelift subscription
Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies.

import-lazy's People

Contributors

bendingbender avatar bfred-it avatar danielhusar avatar fabiospampinato avatar florianb avatar jamestalmage avatar richienb avatar rjoaopereira avatar sindresorhus avatar sonicdoe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

import-lazy's Issues

Consider `laxy`

While not my intention when initially creating laxy, it ended up being a drop in replacement for this module.

It has a few key advantages:

  • It's a more generalized Proxy generator. Allowing for any generator function (not just require), and allows passing any number of arguments.

  • It implements much more of the Proxy API. Allowing things like Object.keys, Object.getPrototypeOf, setting values, and reflecting on property descriptors of the underlying object, etc.

  • laxy(require)('modulePath') will work exactly as this module does, so the API is a drop in replacement.

  • Proxy can be made to respond correctly to typeof (import-lazy will always report 'function' regardless of the proxied object).

  • Support for revocable proxies.

  • It has a fun name.

Obviously not all of those are applicable to the goal of lazy importing, but there are a few items worth porting here at a minimum.

TypeScript failure with "Usage with bundlers" example

Hi there,

When I try the "Usage with bundlers" example in README with TypeScript, the following failure occurs:

$ npx tsc
index.js:2:11 - error TS2554: Expected 1 arguments, but got 0.

2 const _ = importLazy(() => require("lodash"))();
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  node_modules/import-lazy/index.d.ts:24:5
    24 ): (moduleId: string) => T;
           ~~~~~~~~~~~~~~~~
    An argument for 'moduleId' was not provided.


Found 1 error.

https://github.com/sindresorhus/import-lazy/tree/4fea4ed97eb932fa997e2d8efeef298d3aa531a7#usage-with-bundlers

I think the moduleId argument should be optional, but I'm not confident:

 declare function importLazy<T>(
 	importFn: (moduleId: string) => T
-): (moduleId: string) => T;
+): (moduleId?: string) => T;
 
 export = importLazy;

import-lazy/index.d.ts

Lines 22 to 24 in 4fea4ed

declare function importLazy<T>(
importFn: (moduleId: string) => T
): (moduleId: string) => T;

What do you think?

Reproduction

  • index.js:
const importLazy = require("import-lazy");
const _ = importLazy(() => require("lodash"))();

_.isNumber("1");
  • package.json:
{
  "dependencies": {
    "@types/lodash": "^4.14.157",
    "@types/node": "^14.0.24",
    "import-lazy": "^4.0.0",
    "lodash": "^4.17.19",
    "typescript": "^3.9.7"
  }
}
  • tsconfig.json:
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "allowJs": true,
    "checkJs": true,
    "noEmit": true
  }
}

Related to #15

'Error: Cannot find module "."' when using webpack

Hi,

I'm using a npm package that has lazi-req as a dependency. I'm using webpack to bundle my application.

The line:

const lazyReq = require('lazy-req')(require);`

is bundled by webpack as the following:

var lazyReq = __webpack_require__("./node_modules/bin-wrapper/node_modules/lazy-req/index.js")(!(function webpackMissingModule() {
    var e = new Error("Cannot find module \".\"");
    e.code = 'MODULE_NOT_FOUND';
    throw e;
}()));

As I understand, webpack replace the require function that should be passed to lazy-req and try to import a module named ., as no name is given. Obviously, it fails.

Is there a way to avoid that ?

Thank you

Improve docs about usage with bundlers

I was trying to lazy-load some expensive modules in my webpack-bundled application and I found this module.

The recommended way of using it is too dynamic for bundlers, as they can't infer what modules are actually getting loaded:

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

But it turns out that this module is general enough to support my use case too:

const importLazy = require('import-lazy');
const _ = importLazy(() => require ( 'lodash' ))();

But the syntax gets a bit weird.

Perhaps this way of using it could be mentioned explicitly in the readme.

Use ES2015 Proxy

Should be in addition to the existing method, as we still need to support Node.js 4. Proxy requires Node.js 6. The benefit of using Proxy is that users can just use the lazy properties as normal instead of having to call them as functions, so it would be a more direct swap-in.

Not something I have time to work on, but a pull request would be more than welcome :)

Drop Node 5 support in v3.0.0

schedule as of may 2017

Node 6 is the current LTS release, Node 5 is not maintained, Node 4 is in maintenance mode.

It'd make sense to push the Proxy version as the default version or as the only version. Who needs Node 4 support can install the current version (v2.x)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.