NodeJS customization hooks to add support for import maps to NodeJS. This allows you to customize module resolution by creating a node.importmap file.
npm install --save @node-loader/import-maps
pnpm install --save @node-loader/import-mapsCreate a file (e.g. node.importmap) in the current working directory:
{
"imports": {
"my-module": "file:///home/name/code/my-module.js"
}
}Now create a file main.js that imports the mapped module:
import"my-module";Now create a startup moduleregister-hooks.js:
import{register}from"node:module";import{MessageChannel}from"node:worker_threads";constmessageChannel=newMessageChannel();global.importMapPort=messageChannel.port1;register("@node-loader/import-maps",import.meta.url,{data: {// optional, provides a way to update the import map later onport: messageChannel.port2,// optional, import map objectimportMap: {imports: {},scopes: {},},// optional, file url resolved relative to current working directory// This option is ignored if importMap is providedimportMapUrl: "./node.importmap",},transferList: [messageChannel.port2],});Now run main.js with the --import NodeJS flag:
node --import ./register-hooks.js main.jsTo dynamically change the import map after startup, do the following:
global.importMapPort.postMessage({// Provide either importMap or importMapUrl, but not bothimportMap: {imports: {},scopes: {},},importMapUrl: "./node.importmap",});