Skip to content

Instantly share code, notes, and snippets.

@ThomasG77
Last active September 23, 2022 11:20
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ThomasG77/15cedc21e23744461191df6ccd4d7b6b to your computer and use it in GitHub Desktop.
Issue for path cli resolving when migrating CommonJS to ES6

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"
  },
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment