I am using ESM in my node project. Added "type": "module" in package.json
// index.js
import config from 'config'
// default.js
export default {
time: 123,
...
...
}
But getting error in node-config
Error: Cannot parse config file: '/home/Documents/.../config/default.js': Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/Documents/.../config/default.js
require() of ES modules is not supported.
require() of /home/Documents/.../config/default.js from /home/Documents/.../node_modules/config/parser.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename default.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/Documents/.../package.json.
I can fix this by adding default.cjs instead of default.js but as I am using ESM so I am expecting it to work with .js extension also. am I missing something??. I can add .json also but I have big config variables and dynamic values that is why using .js.
Thank you in advance !!!
According to https://github.com/node-config/node-config/wiki/Special-features-for-JavaScript-configuration-files you can not use ESM for configuration files but must use one of the other supported formats.
But there is a work-around. For example you could have the following structure, where dynamic.js is where you have big config variables and dynamic values:
You must tell nodejs that you use esm. So in your package.json you will want to have:
In the beginning of your index.js file, you want to import node-config.
In the above case you could write "Hello World!" to your terminal if config/test.cjs and config/dynamic.js has the following:
test.cjs
dynamic.js
The result of the above should then be:
Obviously, you can rename
variableandconfigVariableto what-ever you want.In my test, I had no issue with the above way of exporting esm as a Promise. But if you do get any issue with with that, you might solve it by wrapping
import()inrequire('config/raw').raw. See: https://github.com/node-config/node-config/wiki/Special-features-for-JavaScript-configuration-files#using-promises-processstdout-and-other-objects-in-javascript-config-files.