I'm working on adding support for .js
config file in a NodeJS library. NodeJS support two module system - ESM & CommonJS - and since javascript files with .js
can be treated as an ES Module or a Common JS module based on the what is defined as type parameter in package.json
, I'm not able to figure out, how to know that what module system is a user of the library is using. Based on the module system used by the user only I can decide whether to import config using require()
or import()
Asked
Active
Viewed 106 times
0

Anshul Sahni
- 626
- 8
- 21
-
based on [this](https://nodejs.org/docs/latest/api/packages.html#packagejson-and-file-extensions), I think you just need to add `type: "commonjs"` so both `commonjs` & `module` users can use your library. – bogdanoff Aug 05 '22 at 07:08
1 Answers
0
There isn't a good way too know about the module type of the application code form a node module. One workaround that I can think of would be using something like parent-package-json –
import getParent from 'parent-package-json';
const parent = getParent();
const parentModuleType = parent ? parent.type : DEFAULT_MODULE_TYPE;

tbking
- 8,796
- 2
- 20
- 33