Skip to content

Commit

Permalink
Export lazy object and import to plugins
Browse files Browse the repository at this point in the history
  • Loading branch information
alcuadrado committed Jan 31, 2019
1 parent 9f4db9c commit 00c2def
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 0 deletions.
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -80,6 +80,7 @@
"find-up": "^2.1.0",
"fs-extra": "^7.0.1",
"glob": "^7.1.3",
"import-lazy": "^3.1.0",
"lodash": "^4.17.11",
"mocha": "^5.1.1",
"semver": "^5.6.0",
Expand Down
24 changes: 24 additions & 0 deletions src/internal/util/lazy.ts
Expand Up @@ -81,3 +81,27 @@ export function lazyObject<T extends object>(objectCreator: () => T): T {
}
});
}

/**
* This function is a lazy version of `require`. It imports a module
* synchronously, by creating a proxy that delays the actual `require` until
* the module is used.
*
* The disadvantage of using this technique is that the type information is
* lost. If done with enough care, this can be manually fixed.
*
* TypeScript doesn't emit `require` calls for modules that are imported only
* because of their types. So if one uses lazyImport along with a normal ESM
* import you can pass the module's type to this function.
*
* An example of this can be:
*
* `import ModType from "mod";`
* `const Mod = lazyImport<ModType>("mod");`
*/
export function lazyImport<ModuleT = any>(packageName: string): ModuleT {
const importLazy = require("import-lazy");
const lazyRequire = importLazy(require);

return lazyRequire(packageName);
}
1 change: 1 addition & 0 deletions src/plugins.ts
Expand Up @@ -4,3 +4,4 @@ export {
readArtifact,
readArtifactSync
} from "./internal/artifacts";
export { lazyObject, lazyImport } from "./internal/util/lazy";
5 changes: 5 additions & 0 deletions yarn.lock
Expand Up @@ -1772,6 +1772,11 @@ ieee754@^1.1.4:
resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.1.12.tgz#50bf24e5b9c8bb98af4964c941cdb0918da7b60b"
integrity sha512-GguP+DRY+pJ3soyIiGPTvdiVXjZ+DbXOxGpXn3eMvNW4x4irjqXm4wHKscC+TfxSJ0yw/S1F24tqdMNsMZTiLA==

import-lazy@^3.1.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/import-lazy/-/import-lazy-3.1.0.tgz#891279202c8a2280fdbd6674dbd8da1a1dfc67cc"
integrity sha512-8/gvXvX2JMn0F+CDlSC4l6kOmVaLOO3XLkksI7CI3Ud95KDYJuYur2b9P/PUt/i/pDAMd/DulQsNbbbmRRsDIQ==

imurmurhash@^0.1.4:
version "0.1.4"
resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea"
Expand Down

0 comments on commit 00c2def

Please sign in to comment.