I've been looking for a way to inject a configuration file like process.cwd()+"/my-config.js"
into a configuration file in a node package I work on. The problem with dynamic import(process.cwd()+"/my-config.js")
is, that is async. But the underlying tools need my config file to be sync.
Searching for "node synchronous dynamic import" I found the answer on stackoverflow: "Convert import() to synchronous".
There is a functionality in Node for that: module.createRequire(filename)
(see the docs)
// node_modules/my-package/config.js
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const userConfig = require(`${process.cwd()}/my-config.js`);
export const config = {
property1: "fallback-value",
...userConfig.config,
};
Editing-Notes: 1. IRL I'd use path.join(process.cwd(), "my-config.js")
. 2. I was not able to nest \
` in order to show inline code for template strings.
Top comments (0)