Ask questionsESM importing a CommonJS calls getters
pg npm dependency
Run the following module:
import pg from 'pg'; console.log(!!pg);
It always reproduces. The imported module needs to be a CommonJS module with getters.
In this case
pg exports a getter that lazily tries to load another npm package: https://github.com/brianc/node-postgres/blob/master/packages/pg/lib/index.js#L32-L55
$ node -v v14.12.0 $ node pg.mjs true
$ node -v v14.13.0 $ node pg.mjs Cannot find module 'pg-native' Require stack: - /dev/temp/node-bugs/node_modules/pg/lib/native/client.js - /dev/temp/node-bugs/node_modules/pg/lib/native/index.js - /dev/temp/node-bugs/node_modules/pg/lib/index.js true
This change was introduced in https://github.com/nodejs/node/pull/35249
Answer questions avaly
npm install pg-nativeto fix really that bad?
If it were any other dependency, that wouldn't be an issue. But in this case, this dependency requires build tools to be installed to build a native binary (https://www.npmjs.com/package/pg-native). It's not something one should be forced to do, if we don't plan on using that part of the library.
TBH I would also like to see a change in how the
pg library is exporting its native part. So maybe it's not actionable from node.js itself.
But what about other packages that may be using a similar pattern?