From 60e094c63ceadc3c63313f14b1d60bcd719faab6 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Wed, 26 Jan 2022 12:44:36 +0100 Subject: [PATCH] fix: move esm resolve behind a flag --- README.md | 8 ++++++++ src/jiti.ts | 27 ++++++++++++++++----------- src/types.ts | 1 + 3 files changed, 25 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index cea9364d..85cbc67d 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,14 @@ Use transpile cache If set to `true` will use `node_modules/.cache/jiti` (if exists) or `{TMP_DIR}/node-jiti` +### `esmResolve` + +- Type: Boolean | String +- Default: `false` +- Environment Vriable: `JITI_ESM_RESOLVE` + +Using esm resolution algorithm to support `import` condition. + ### `transform` - Type: Function diff --git a/src/jiti.ts b/src/jiti.ts index 95f68c60..14cb72f2 100644 --- a/src/jiti.ts +++ b/src/jiti.ts @@ -16,6 +16,7 @@ import { TransformOptions, JITIOptions } from './types' const _EnvDebug = destr(process.env.JITI_DEBUG) const _EnvCache = destr(process.env.JITI_CACHE) +const _EnvESMReolve = destr(process.env.JITI_ESM_RESOLVE) const _EnvRequireCache = destr(process.env.JITI_REQUIRE_CACHE) const defaults: JITIOptions = { @@ -23,6 +24,7 @@ const defaults: JITIOptions = { cache: _EnvCache !== undefined ? !!_EnvCache : true, requireCache: _EnvRequireCache !== undefined ? !!_EnvRequireCache : true, interopDefault: false, + esmResolve: _EnvESMReolve || false, cacheVersion: '6', legacy: lt(process.version || '0.0.0', '14.0.0'), extensions: ['.js', '.mjs', '.cjs', '.ts'] @@ -84,18 +86,21 @@ export default function createJITI (_filename: string, opts: JITIOptions = {}, p const _url = pathToFileURL(_filename) const _additionalExts = [...opts.extensions!].filter(ext => ext !== '.js') const _resolve = (id: string, options?: { paths?: string[] }) => { - // Try ESM resolve let resolved, err - try { - resolved = resolvePathSync(id, { - url: _url, - conditions: ['node', 'require', 'import'] - }) - } catch (_err) { - err = _err - } - if (resolved) { - return resolved + + // Try ESM resolve + if (opts.esmResolve) { + try { + resolved = resolvePathSync(id, { + url: _url, + conditions: ['node', 'require', 'import'] + }) + } catch (_err) { + err = _err + } + if (resolved) { + return resolved + } } // Try native require resolve diff --git a/src/types.ts b/src/types.ts index fcd84f31..ccff6f5d 100644 --- a/src/types.ts +++ b/src/types.ts @@ -20,6 +20,7 @@ export type JITIOptions = { requireCache?: boolean v8cache?: boolean interopDefault?: boolean + esmResolve?: boolean, cacheVersion?: string onError?: (error: Error) => void legacy?: boolean