DEV Community

Hauke T.
Hauke T.

Posted on

TIL: Synchronous import in ES-Modules using module.createRequire (Node)

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,
}; 
Enter fullscreen mode Exit fullscreen mode

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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs