Git Product home page Git Product logo

import-meta-resolve's Introduction

import-meta-resolve

Build Coverage Downloads

Resolve things like Node.js.

Contents

What is this?

This package is a ponyfill for import.meta.resolve. It supports everything you need to resolve files just like modern Node does: import maps, export maps, loading CJS and ESM projects, all of that!

When to use this?

As of Node.js 20.0, import.meta.resolve is still behind an experimental flag. This package can be used to do what it does in Node 16–20.

Install

This package is ESM only. In Node.js (version 16+), install with npm:

npm install import-meta-resolve

Use

import {resolve} from 'import-meta-resolve'

// A file:
console.log(resolve('./index.js', import.meta.url))
//=> file:///Users/tilde/Projects/oss/import-meta-resolve/index.js

// A CJS package:
console.log(resolve('builtins', import.meta.url))
//=> file:///Users/tilde/Projects/oss/import-meta-resolve/node_modules/builtins/index.js

// A scoped CJS package:
console.log(resolve('@eslint/eslintrc', import.meta.url))
//=> file:///Users/tilde/Projects/oss/import-meta-resolve/node_modules/@eslint/eslintrc/lib/index.js

// A package with an export map:
console.log(resolve('micromark/lib/parse', import.meta.url))
//=> file:///Users/tilde/Projects/oss/import-meta-resolve/node_modules/micromark/lib/parse.js

// A node builtin:
console.log(resolve('fs', import.meta.url))
//=> node:fs

API

This package exports the identifiers moduleResolve and resolve. There is no default export.

resolve(specifier, parent)

Match import.meta.resolve except that parent is required (you can pass import.meta.url).

Parameters
  • specifier (string) — the module specifier to resolve relative to parent (/example.js, ./example.js, ../example.js, some-package, fs, etc)
  • parent (string, example: import.meta.url) — the absolute parent module URL to resolve from; you must pass import.meta.url or something else
Returns

Full file:, data:, or node: URL (string) to the found thing

Throws

Throws an ErrnoException.

moduleResolve(specifier, parent, conditions, preserveSymlinks)

The “Resolver Algorithm Specification” as detailed in the Node docs (which is slightly lower-level than resolve).

Parameters
  • specifier (string) — /example.js, ./example.js, ../example.js, some-package, fs, etc
  • parent (URL, example: import.meta.url) — full URL (to a file) that specifier is resolved relative from
  • conditions (Set<string>, default: new Set(['node', 'import'])) — conditions
  • preserveSymlinks (boolean, default: false) — keep symlinks instead of resolving them
Returns

A URL object (URL) to the found thing.

Throws

Throws an ErrnoException.

ErrnoException

One of many different errors that occur when resolving (TypeScript type).

Type
type ErrnoExceptionFields = Error & {
  errnode?: number | undefined
  code?: string | undefined
  path?: string | undefined
  syscall?: string | undefined
  url?: string | undefined
}

The code field on errors is one of the following strings:

  • 'ERR_INVALID_MODULE_SPECIFIER' — when specifier is invalid (example: '#')
  • 'ERR_INVALID_PACKAGE_CONFIG' — when a package.json is invalid (example: invalid JSON)
  • 'ERR_INVALID_PACKAGE_TARGET' — when a package.json exports or imports is invalid (example: when it does not start with './')
  • 'ERR_MODULE_NOT_FOUND' — when specifier cannot be found in parent (example: 'some-missing-package')
  • 'ERR_NETWORK_IMPORT_DISALLOWED' — thrown when trying to resolve a local file or builtin from a remote file (node:fs relative to 'https://example.com')
  • 'ERR_PACKAGE_IMPORT_NOT_DEFINED' — when a local import is not defined in an import map (example: '#local' when not defined)
  • 'ERR_PACKAGE_PATH_NOT_EXPORTED' — when an export is not defined in an export map (example: 'tape/index.js', which is not in its export map)
  • 'ERR_UNSUPPORTED_DIR_IMPORT' — when attempting to import a directory (example: './lib/')
  • 'ERR_UNKNOWN_FILE_EXTENSION' — when somehow reading a file that has an unexpected extensions ('./readme.md')
  • 'ERR_INVALID_ARG_VALUE' — when conditions is incorrect

Algorithm

The algorithm for resolve matches how Node handles import.meta.resolve, with a couple of differences.

The algorithm for moduleResolve matches the Resolver Algorithm Specification as detailed in the Node docs (which is sync and slightly lower-level than resolve).

Differences to Node

  • parent defaulting to import.meta.url cannot be ponyfilled: you have to explicitly pass it
  • no support for loaders (that would mean implementing all of loaders)
  • no support for CLI flags: --conditions, --experimental-default-type, --experimental-json-modules, --experimental-network-imports, --experimental-policy, --experimental-wasm-modules, --input-type, --no-addons, --preserve-symlinks, nor --preserve-symlinks-main work
  • no support for WATCH_REPORT_DEPENDENCIES env variable
  • no attempt is made to add a suggestion based on how things used to work in CJS before to not-found errors
  • prototypal methods are not guarded: Node protects for example String#slice or so from being tampered with, whereas this doesn’t

Types

This package is fully typed with TypeScript. It exports the additional type ErrnoException.

Compatibility

This package is at least compatible with all maintained versions of Node.js. As of now, that is Node.js 16 and later.

Contribute

Yes please! See How to Contribute to Open Source.

License

MIT © Titus Wormer and Node.js contributors

import-meta-resolve's People

Contributors

brawaru avatar giltayar avatar ifiokjr avatar jakebailey avatar kapouer avatar perrin4869 avatar sosukesuzuki avatar wooorm 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

import-meta-resolve's Issues

Yarn PnP compatibility?

I believe the issue described here (remarkjs/remark-language-server#6 (comment)) is a result of an assumption that packages are stored in a node_modules directory.

I tried running resolve against my project and got the following error

% yarn node test.mjs
file:///<mycwd>/.yarn/cache/import-meta-resolve-npm-2.1.0-fcf1208127-4554ea5e2d.zip/node_modules/import-meta-resolve/lib/errors.js:322
    Error.captureStackTrace(error)
          ^

Error: Cannot find package 'remark' imported from /<mycwd>/test.mjs
    at new NodeError (file:///<mycwd>/.yarn/cache/import-meta-resolve-npm-2.1.0-fcf1208127-4554ea5e2d.zip/node_modules/import-meta-resolve/lib/errors.js:276:5)
    at packageResolve (file:///<mycwd>/.yarn/cache/import-meta-resolve-npm-2.1.0-fcf1208127-4554ea5e2d.zip/node_modules/import-meta-resolve/lib/resolve.js:1060:9)
    at moduleResolve (file:///<mycwd>/.yarn/cache/import-meta-resolve-npm-2.1.0-fcf1208127-4554ea5e2d.zip/node_modules/import-meta-resolve/lib/resolve.js:1117:20)
    at defaultResolve (file:///<mycwd>/.yarn/cache/import-meta-resolve-npm-2.1.0-fcf1208127-4554ea5e2d.zip/node_modules/import-meta-resolve/lib/resolve.js:1266:15)
    at resolve (file:///<mycwd>/.yarn/cache/import-meta-resolve-npm-2.1.0-fcf1208127-4554ea5e2d.zip/node_modules/import-meta-resolve/index.js:29:12)
    at file:///<mycwd>/test.mjs:20:19
    at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:533:24) {
  code: 'ERR_MODULE_NOT_FOUND'
}

where test.mjs is

import {resolve} from 'import-meta-resolve'

console.log(await resolve('remark', import.meta.url))
  • remark is installed
  • I'm using Yarn PnP, where packages are in .yarn/cache/... rather than node_modules
  • Node 16.17.0, Yarn 3.2.3

A more thorough example:

test2.mjs

import {resolve} from 'import-meta-resolve';
import * as remark from 'remark';
import { createRequire } from 'module';

const require = createRequire(import.meta.url);

console.log('remark:', typeof remark, '\n');
console.log('require.resolve:', require.resolve('remark'), '\n');
console.log('import-meta-resolve:');
console.log(await resolve('remark', import.meta.url));

Yields:

remark: object 

require.resolve: /<mycwd>/.yarn/cache/remark-npm-14.0.2-9e7a75b6a9-a534b6c6bb.zip/node_modules/remark/index.js 

import-meta-resolve:
file:///<mycwd>/.yarn/cache/import-meta-resolve-npm-2.1.0-fcf1208127-4554ea5e2d.zip/node_modules/import-meta-resolve/lib/errors.js:322
    Error.captureStackTrace(error)
          ^

Error: Cannot find package 'remark' imported from /<mycwd>/test.mjs
    at new NodeError (file:///<mycwd>/.yarn/cache/import-meta-resolve-npm-2.1.0-fcf1208127-4554ea5e2d.zip/node_modules/import-meta-resolve/lib/errors.js:276:5)
    at packageResolve (file:///<mycwd>/.yarn/cache/import-meta-resolve-npm-2.1.0-fcf1208127-4554ea5e2d.zip/node_modules/import-meta-resolve/lib/resolve.js:1060:9)
    at moduleResolve (file:///<mycwd>/.yarn/cache/import-meta-resolve-npm-2.1.0-fcf1208127-4554ea5e2d.zip/node_modules/import-meta-resolve/lib/resolve.js:1117:20)
    at defaultResolve (file:///<mycwd>/.yarn/cache/import-meta-resolve-npm-2.1.0-fcf1208127-4554ea5e2d.zip/node_modules/import-meta-resolve/lib/resolve.js:1266:15)
    at resolve (file:///<mycwd>/.yarn/cache/import-meta-resolve-npm-2.1.0-fcf1208127-4554ea5e2d.zip/node_modules/import-meta-resolve/index.js:29:12)
    at file:///<mycwd>/test.mjs:10:19
    at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:533:24) {
  code: 'ERR_MODULE_NOT_FOUND'
}

Circular dependency in lib/get-format.js

Heyo! Thanks so much for maintaining this package, it's been incredibly useful so far (while Node.js is still keeping this feature experimental) 🙌🏻

Unfortunately I have hit an error today with jiti package (when used in Nuxt, but more precisely it's coming from c12 that Nuxt uses to load configurations). The error caused by the circular dependency in lib/get-format.js, because of it jiti gets stuck in a recursion until it errors out due to exceeding the stack size.

It would've been a relatively simple change to fix it — just to move the getPackageType into its own file, but as I understand from the comments in code, you grab the code directly from Node.js. I'm a bit worried that I'm in no capacity to contribute that directly to Node.js, and creating an issue about that probably won't bring fix any soon (although I may try), but I really need that fixed (currently using pnpm patching, but that's not a solution you can ship to package consumers).

So I'm wondering if you would be okay with accepting a PR with the above commit if I were to submit it?

Support for resolving modules from folder paths

I spent some time trying to resolve a dependency from a URL like the following, which was a bit confusing because I have that dependency listed in package.json, installed in node_modules and I can import it from the REPL, but this module can't find it:

url.pathToFileURL(process.cwd());

But apparently using a folder's path as the starting point is not supported, while something like this works:

url.pathToFileURL(path.join(process.cwd(), "index.js"));

IMO it'd be nice if resolving from a folder was just supported also, or at least if this scenario was documented.

Issues with loading from ESM, "type": "module", & rollup

I ran across an issue with loading this library from an ESM & have since vendorized it with a forked repo & custom build to fix the problem. I'm creating this issue to track the changes. I'll investigate if there is any problem with this package of if it's a problem with a dependency.

builtins is a dependency with a loading issue from ESM. juliangruber/builtins#37

Please keep this issue open until I can provide more detail. Thank you.

Enabling usage of this package in an eslint plugin

Context: I'm trying to help revive eslint-plugin-node, using a fork someone created (https://www.npmjs.com/package/eslint-plugin-node).

The first issue I wanted to fix is that eslint-plugin-node errs on packages that have no main in theirpackage.json. This is because it uses @ljharb's resolve package which doesn't yet cover the new exports field. I looked for a replacement package, and yours fit the bill.

Unfortunately, it's ESM-only, and ESLint is CJS. And... I can't await import it, because ESLint doesn't support async plugins anywhere in their API (at least I couldn't find anything).

So... any chance you would be willing to accept a PR that turns this into a dual-mode package? I know you're very much on the ESM-only bandwagon, but... maybe? I would do it the usual way: a build process to transpile it into CJS using rollup or babel, and package it as dual-mode. Should work.

(and, yes, the API is async, but I noticed that it isn't really, so I could create a sync version)

Support for TypeScript files

Description

Is it possible to add builtin support for .ts, .mts and .cts files?

I'm using this library and running tests on a TypeScript monorepo codebase. During development the "exports" field entrypoints redirect to TypeScript files via symlinks. This breaks with the following error.

ERR_UNKNOWN_FILE_EXTENSION - Unknown file extension ".ts" for X

I'm happy to open a PR and add the extensions, if you think it's a good idea.

/** @type {Record<string, string>} */
const extensionFormatMap = {
// @ts-expect-error: hush.
__proto__: null,
'.cjs': 'commonjs',
'.js': 'module',
'.json': 'json',
'.mjs': 'module'
}

First item is always resolved when export map target is Array (even if non-existent)

Current Behavior

Given the following exports map:

  "name": "example",
  "exports": {
    "./a": [
      "./b.js",
      "./non-existent.js"
    ],
    "./c": [
      "./non-existent.js",
      "./d.js"
    ]
  }

Where ./non-existent.js does not exist on disk, the following holds true:

import thing1 from "example/a" // imports from "example/b.js"
import thing2 from "example/c" // imports from "example/non-existent.js"

Expected Behavior

"example/c" should resolve to "example/d.js" when "./non-existent.js" is not found.

Reproduction

I've added tests that cover both cases in the associated PR. The first passes, but the second fails the strictEqual assertion.

Additional Info

I took a swing at fixing this, but no luck. The packageExportsResolve algorithm calls resolvePackageTarget when it finds a match in the exports field. resolvePackageTarget does check if target is an array, but it greedily accepts the first entry unless it throws ERR_INVALID_PACKAGE_TARGET. However, the target technically is a valid target—it just doesn't point to an existing file.

My first thought was to call fileExists(resolved) just before returning out of the loop on line 540, and, if false, continue the loop to the next item. Unfortunately that didn't seem to work for some reason.

while (++i < targetList.length) {

My next thought was that one of the other resolver functions was returning a result before the packageExportsResolve ever gets called, short-circuiting it.

Unfortunately, it seems I can't get any of my breakpoints to fire when I run it in the debugger, nor can I get any console.log calls to print to the terminal. Any ideas what might be going on here?

Resolve fails on MacOS and Windows, works on linux

We have a SvelteKit project (which uses your library in version 4.0.0) which runs fine on my Debian VM but fails to resolve a dependency both on a Mac and a Windows machine when using Yarn pnp linker (it works everywhere with Yarn node-modules liker though).

After clearing out any other reason (fresh branch checkout on all machines, no changes...) I had to trace the code, and I ended up looking into SvelteKit code and figured the following line didn't behave the same between platforms:

const resolved = await imr.resolve(dependency, pathToFileURL(process.cwd() + '/dummy.js'));

On my linux VM I get a path, on the other machine an exception. On this line imr is being imported from your library with: import * as imr from 'import-meta-resolve';.

Since I use Node 20, I tried changing the line to:

const resolved = import.meta.resolve(dependency, pathToFileURL(process.cwd() + '/dummy.js'));

And everything works on all machines.

For reference, this is the location of the call in the SvelteKit project: https://github.com/sveltejs/kit/blob/a6333a5d0833781c6572098a6240976e84fb5150/packages/kit/src/exports/vite/index.js#L134

I must admit I don't have a clue as to what causes the issue, in particular we have no space in the paths and they are reasonable in length (48 to 65 characters depending on platform).

Don't hesitate to let me know if there a place where I could look for more details to help solve this.

Incompatible with yarn P'n'P

Same as #10

See also conventional-changelog/commitlint#3936

I also tried yarn unplug:

{
  "dependenciesMeta": {
    "@commitlint/config-conventional": {
      "unplugged": true
    },
    "@commitlint/[email protected]": {
      "unplugged": true
    },
    "import-meta-resolve": {
      "unplugged": true
    }
  }
}
file:///Users/JounQin/.yarn/berry/cache/@commitlint-cli-npm-19.0.1-8d41b28200-10.zip/node_modules/@commitlint/cli/lib/cli.js:129
        throw err;
        ^

Error: Cannot find module "@commitlint/config-conventional" from "/Users/JounQin/Workspaces/GitHub/test"
    at resolveId (file:///Users/JounQin/Workspaces/GitHub/test/.yarn/unplugged/@commitlint-resolve-extends-npm-19.0.1-78a2e74462/node_modules/@commitlint/resolve-extends/lib/index.js:158:17)
    at tryResolveId (file:///Users/JounQin/Workspaces/GitHub/test/.yarn/unplugged/@commitlint-resolve-extends-npm-19.0.1-78a2e74462/node_modules/@commitlint/resolve-extends/lib/index.js:145:12)
    at resolveConfig (file:///Users/JounQin/Workspaces/GitHub/test/.yarn/unplugged/@commitlint-resolve-extends-npm-19.0.1-78a2e74462/node_modules/@commitlint/resolve-extends/lib/index.js:132:20)
    at file:///Users/JounQin/Workspaces/GitHub/test/.yarn/unplugged/@commitlint-resolve-extends-npm-19.0.1-78a2e74462/node_modules/@commitlint/resolve-extends/lib/index.js:96:26
    at Array.reduce (<anonymous>)
    at loadExtends (file:///Users/JounQin/Workspaces/GitHub/test/.yarn/unplugged/@commitlint-resolve-extends-npm-19.0.1-78a2e74462/node_modules/@commitlint/resolve-extends/lib/index.js:95:22)
    at resolveExtends (file:///Users/JounQin/Workspaces/GitHub/test/.yarn/unplugged/@commitlint-resolve-extends-npm-19.0.1-78a2e74462/node_modules/@commitlint/resolve-extends/lib/index.js:76:28)
    at load (file:///Users/JounQin/.yarn/berry/cache/@commitlint-load-npm-19.0.1-947ecbb8ee-10.zip/node_modules/@commitlint/load/lib/load.js:44:28)
    at async main (file:///Users/JounQin/.yarn/berry/cache/@commitlint-cli-npm-19.0.1-8d41b28200-10.zip/node_modules/@commitlint/cli/lib/cli.js:202:20) {
  code: 'MODULE_NOT_FOUND'
}

Reproduction: https://github.com/JounQin/test/tree/repro/commitlint

Steps:

  1. yarn install
  2. yarn commitlint --from

Related source codes:

let packageJsonUrl = new URL(
'./node_modules/' + packageName + '/package.json',
base
)
let packageJsonPath = fileURLToPath(packageJsonUrl)
/** @type {string} */
let lastPath
do {
const stat = tryStatSync(packageJsonPath.slice(0, -13))
if (!stat.isDirectory()) {
lastPath = packageJsonPath
packageJsonUrl = new URL(
(isScoped ? '../../../../node_modules/' : '../../../node_modules/') +
packageName +
'/package.json',
packageJsonUrl
)
packageJsonPath = fileURLToPath(packageJsonUrl)
continue
}
// Package match.
const packageConfig = packageJsonReader.read(packageJsonPath, {
base,
specifier
})
if (packageConfig.exports !== undefined && packageConfig.exports !== null) {
return packageExportsResolve(
packageJsonUrl,
packageSubpath,
packageConfig,
base,
conditions
)
}
if (packageSubpath === '.') {
return legacyMainResolve(packageJsonUrl, packageConfig, base)
}
return new URL(packageSubpath, packageJsonUrl)
// Cross-platform root check.
} while (packageJsonPath.length !== lastPath.length)
throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath(base), false)

exporting the `packageResolve` function

Hey there 👋 Thanks for developing this great package!

I am working on an ESM version of import-from (ingeniously named import-from-esm), for which I needed to emulate require's behavior using ESM dynamic import.

I found a function (packageResolve) in your library that saved me 99% of the work, and by using it I don't have to implement node_modules tree traversal, export maps resolution, etc...

Because that function isn't exported by your package, I have copied the sources (and license) from import-meta-resolve/lib/, exported the packageResolve function, removed the resolve & moduleResolve functions, and pruned unused code.

As discussed on semantic-release/release-notes-generator#544 (comment), it would be best to directly use your library for updates and security concerns, if you'd agree to export the packageResolve function (without necessarily documenting it).

Please let me know if you'd be okay with that, or if there are any concerns on your mind!

Make this work with yarn berry (aka yarn 2/3/4)

Currently prettier, which uses import-meta-resolve does not work with yarn berry using PnP (the default node linker): yarnpkg/berry#6167.

This effectively breaks sveltkit when used with yarn berry.

I have been able to fix the problem in prettier by changing the importFromFile function as follows:

function importFromFile(specifier, parent) {
  if (process.versions.pnp) {
    const { createRequire } = require('module');
    const targetRequire = createRequire(parent);
    const resolved = targetRequire.resolve(specifier);
    return targetRequire(resolved);
  } else {
    const url2 = resolve2(specifier, pathToFileURL4(parent).href);
    return import(url2);
  }
}

However, the real fix should be implemented in import-meta-resolve rather than prettier (the fix can be essentially the same).

You can easily reproduce the issue using the steps in the above yarn issue.

I'm happy to help with making the fix if it's something you will accept. Currently I have to patch it in prettier since import-meta-resolve is embedded in there distribution.

Want help on maintenance?

Hi dear @wooorm and thanks for your nice package ❤️

We have adopted import-meta-resolve (inline for packaging issues) for unjs/mlly that is used by nuxt and some other libs with over 1.5M monthly downloads.

I have discovered there are some upstream fixes in Node.js that need to be applied to both packages (here is a summary: unjs/mlly#134). I thought it would be a good chance to move import-meta-resolve to unjs ecosystem to make sure both packages leverage from latest updates and also allowing to use it as external package for mlly.

If you prefer not to, i will remember to make a backport PR for upstream changes.

Cheers.

Possible to use worker threads and execArgv?

In theory, I think the following is possible:

export default function resolve(specifier, parentURL = undefined) {
  if (parentURL == null) {
    if (this?.url != null) {
      parentURL = this.url
    } else {
      parentURL = getParentURLUsingErrorStack()
    }
  }
  const sab = new SharedArrayBuffer(4)
  const lock = new Int32Array(sab)
  const worker = new worker_threads.Worker(`
    const sab = worker_threads.workerData
    const lock = new Int32Array(sab)
    worker_threads.parentPort.on("message", ([specifier, parentURL]) => {
      const resolved = await import.meta.resolve(specifier, parentURL)
      worker_threads.parentPort.postMessage(resolved)
      Atomics.store(lock, 0, 1)
      Atomics.notify(lock, 0)
    })
  `, {
    eval: true,
    //          👇 This is the cool idea? Maybe this works?
    execArgv: ["--experimental-import-meta-resolve", ...process.execArgv],
    workerData: sab
  })
  worker.postMessage([specifier, parentURL])
  Atomics.wait(lock, 0, 0)
  return recieveMessageOnPort(worker)
}

No this code doesn't work as-is.

import resolve from "import-meta-resolve"
import.meta.resolve = resolve;

console.log(import.meta.resolve("my-npm-package"))
//=> 'file:///node_modules/my-npm-package/index.js'

Obviously there's some hiccups that would need to be finagled with and solved, but I think this might work!

[DEP0180] DeprecationWarning: fs.Stats constructor is deprecated in Node v22.0.0

Hi, I received a deprecation warning when running babel using node v22.0.0.
And based on the error message, it seems the warning originated from the import-meta-resolve package babel is using:

(node:241428) [DEP0180] DeprecationWarning: fs.Stats constructor is deprecated.
    at tryStatSync (<REDACTED>/node_modules/.pnpm/@[email protected]/node_modules/@babel/core/lib/vendor/import-meta-resolve.js:511:12)
    at packageResolve (<REDACTED>/node_modules/.pnpm/@[email protected]/node_modules/@babel/core/lib/vendor/import-meta-resolve.js:889:18)
    at moduleResolve (<REDACTED>/node_modules/.pnpm/@[email protected]/node_modules/@babel/core/lib/vendor/import-meta-resolve.js:937:20)
    at defaultResolve (<REDACTED>/node_modules/.pnpm/@[email protected]/node_modules/@babel/core/lib/vendor/import-meta-resolve.js:1007:15)
    at resolve (<REDACTED>/node_modules/.pnpm/@[email protected]/node_modules/@babel/core/lib/vendor/import-meta-resolve.js:1020:12)
    at tryImportMetaResolve (<REDACTED>/node_modules/.pnpm/@[email protected]/node_modules/@babel/core/lib/config/files/plugins.js:142:45)
    at resolveStandardizedNameForImport (<REDACTED>/node_modules/.pnpm/@[email protected]/node_modules/@babel/core/lib/config/files/plugins.js:164:19)
    at resolveStandardizedName (<REDACTED>/node_modules/.pnpm/@[email protected]/node_modules/@babel/core/lib/config/files/plugins.js:173:22)
    at loadPlugin (<REDACTED>/node_modules/.pnpm/@[email protected]/node_modules/@babel/core/lib/config/files/plugins.js:52:20)
    at loadPlugin.next (<anonymous>)
    ...

Apparently calling fs.Stats class directly with Stats() or new Stats() is being deprecated in node v22.0.0:

function tryStatSync(path) {
// Note: from Node 15 onwards we can use `throwIfNoEntry: false` instead.
try {
return statSync(path)
} catch {
return new Stats()
}
}

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.