Skip to main content
100%

Issue for path cli resolving when migrating CommonJS to ES6

✓ Published0🌍 Public
TThomasG77
Last edited Sep 23, 2022
Created on Sep 23, 2022

This example tracks a path-resolution error that occurs when migrating a command-line tool from CommonJS to ES6 modules. It shows the same `require('..')` call working in CommonJS while its ES6 equivalent, `import {parse} from '../index.js'`, fails with `ERR_MODULE_NOT_FOUND` because the ES6 resolver does not search the `lib` directory. The visualization documents the failing command, the package.json configuration that sets `"main": "./lib"`, and the proposed fix of writing the import as `'../lib/index.js'` instead. The data comes directly from the user’s error trace and file contents.

AI-generated description

Path issue when migrating CommonJS to ES6

Context: migrating to ES6 syntax because some upcoming deps ES6 based (want to avoid transpiling)

Command used to fail

Root of the repo myrepo then running

In CommonJS cli

./bin/cli.js < myinput => working

With migrated ES6 version, same command and get the following error

node:internal/errors:464
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/home/myhome/git/myrepo/index.js' imported from /home/myhome/git/myrepo/bin/cli.js
    at new NodeError (node:internal/errors:371:5)
    at finalizeResolution (node:internal/modules/esm/resolve:416:11)
    at moduleResolve (node:internal/modules/esm/resolve:932:10)
    at defaultResolve (node:internal/modules/esm/resolve:1044:11)
    at ESMLoader.resolve (node:internal/modules/esm/loader:422:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:222:40)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:76:40)
    at link (node:internal/modules/esm/module_job:75:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}

Could solve issue with import {parse} from '../lib/index.js' instead of import {parse} from '../index.js' as my main entry point is in lib/index.js but I do not like to not understand why CommonJS syntax can solve the path to lib and ES6 can't. FYI, CommonJS syntax was const {parse} = require('..')

Content of bin/cli.js file

Syntax in bin/cli.js (CommonJS)

const {parse} = require('..')

Syntax in bin/cli.js (ES6)

import {parse} from '../index.js'

package.json section content

package.json section in CommonJS

  "main": "./lib",
  "type": "module",
  "bin": {
    "mybinaryalias": "bin/cli.js"
  },

ES6 case

  "main": "./lib",
  "exports": "./lib", //Tried adding exports
  "type": "module",
  "bin": {
    "mybinaryalias": "bin/cli.js"
  },

Similar vizzes