TS-ESNode icon indicating copy to clipboard operation
TS-ESNode copied to clipboard

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath is not defined by "exports"

Open yoursunny opened this issue 4 years ago • 0 comments

If a TypeScript file imports an NPM package whose package.json contains subpath exports, the loader crashes with Error [ERR_PACKAGE_PATH_NOT_EXPORTED].

Files to Reproduce

package.json

{
  "private": true,
  "type": "module",
  "scripts": {
    "build": "tsc --noEmit",
    "dev": "node --loader @k-foss/ts-esnode --experimental-specifier-resolution=node main.ts"
  },
  "dependencies": {
    "@k-foss/ts-esnode": "^2.0.2",
    "@types/node": "^15.0.2",
    "dotenv": "^9.0.2",
    "typescript": "^4.2.4"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "strict": true,
    "target": "ESNext"
  }
}

main.ts

import dotenv from "dotenv";

dotenv.config();

Error Message

sunny@box1:~/code/bug$ npm run dev

> dev
> node --loader @k-foss/ts-esnode --experimental-specifier-resolution=node main.ts

(node:251905) ExperimentalWarning: --experimental-loader is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
(node:251905) Warning: The dynamicInstantiate loader hook has been removed.
node:internal/process/esm_loader:74
    internalBinding('errors').triggerUncaughtException(
                              ^

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/main.js' is not defined by "exports" in /home/sunny/code/bug/node_modules/dotenv/package.json
    at new NodeError (node:internal/errors:363:5)
    at throwExportsNotFound (node:internal/modules/esm/resolve:321:9)
    at packageExportsResolve (node:internal/modules/esm/resolve:546:3)
    at resolveExports (node:internal/modules/cjs/loader:478:36)
    at Function.Module._findPath (node:internal/modules/cjs/loader:518:31)
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:927:27)
    at Function.Module._load (node:internal/modules/cjs/loader:774:27)
    at Module.require (node:internal/modules/cjs/loader:1013:19)
    at require (node:internal/modules/cjs/helpers:93:18)
    at getSource (file:///home/sunny/code/bug/node_modules/@k-foss/ts-esnode/out/dist/index.js:131:27) {
  code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
}

Analysis

node_modules/dotenv/package.json contains:

{
  "main": "lib/main.js",
  "exports": {
    ".": "./lib/main.js",
    "./config": "./config.js",
    "./package.json": "./package.json"
  }
}

It isn't allowable to require("dotenv/lib/main.js"); due to this subpath exports specification. Instead, the loader should invoke require("dotenv"), i.e. do not resolve export subpath to the actual file.

Environment

  • Node 16.1.0
  • NPM 7.11.2
  • TS-ESNode 2.0.2

yoursunny avatar May 11 '21 02:05 yoursunny