profile
viewpoint

Ask questionsESM importing a CommonJS calls getters

  • Version: 14.13.0
  • Platform: Linux 5.4.0-52-generic #57~18.04.1-Ubuntu SMP Thu Oct 15 14:04:49 UTC 2020 x86_64 GNU/Linux

What steps will reproduce the bug?

Install pg npm dependency

Run the following module:

import pg from 'pg';

console.log(!!pg);

How often does it reproduce? Is there a required condition?

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

What is the expected behavior?

$ node -v
v14.12.0

$ node pg.mjs 
true

What do you see instead?

$ 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

Additional information

This change was introduced in https://github.com/nodejs/node/pull/35249

nodejs/node

Answer questions avaly

Is npm install pg-native to 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?

useful!
source:https://uonfu.com/
Github User Rank List