Context: migrating to ES6 syntax because some upcoming deps ES6 based (want to avoid transpiling)
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('..')
Syntax in bin/cli.js (CommonJS)
const {parse} = require('..')
Syntax in bin/cli.js (ES6)
import {parse} from '../index.js'
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"
},