From 00c2def7bd944c580b7e25b4bb0a5b62555a3eb3 Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Thu, 31 Jan 2019 16:10:06 -0300 Subject: [PATCH] Export lazy object and import to plugins --- package.json | 1 + src/internal/util/lazy.ts | 24 ++++++++++++++++++++++++ src/plugins.ts | 1 + yarn.lock | 5 +++++ 4 files changed, 31 insertions(+) diff --git a/package.json b/package.json index 186af5fb79c..e26a1fb6c69 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/internal/util/lazy.ts b/src/internal/util/lazy.ts index d1921eceadd..4c459858f8f 100644 --- a/src/internal/util/lazy.ts +++ b/src/internal/util/lazy.ts @@ -81,3 +81,27 @@ export function lazyObject(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("mod");` + */ +export function lazyImport(packageName: string): ModuleT { + const importLazy = require("import-lazy"); + const lazyRequire = importLazy(require); + + return lazyRequire(packageName); +} diff --git a/src/plugins.ts b/src/plugins.ts index f98d4edad9b..1dd7f76cac0 100644 --- a/src/plugins.ts +++ b/src/plugins.ts @@ -4,3 +4,4 @@ export { readArtifact, readArtifactSync } from "./internal/artifacts"; +export { lazyObject, lazyImport } from "./internal/util/lazy"; diff --git a/yarn.lock b/yarn.lock index 4d94b791257..e4c3943cef7 100644 --- a/yarn.lock +++ b/yarn.lock @@ -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"