Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS custom loader for CommonJS

I'm playing with NodeJS loaders where I want to intercept all calls to require and modify the source (transpile). When using ESM modules with import it works, but with CommonJS it doesn't trigger the loader when calling require.

Here is the loader code:

async function load(url, context, nextLoad) {
  console.log({ url, context })
  return nextLoad(url)
}

async function resolve(specifier, context, nextResolve) {
  console.log({ specifier, context })
  return nextResolve(specifier)
}

module.exports = { load, resolve }

I'm injecting the loader by running node --loader=./loader.js hello.js from terminal.

And here is the CommonJS code for hello.js:

var lib = require('./lib.js')

The require('./lib.js') line neither triggers the loader resolve nor the load functions in the loader.

If I rewrite using ESM .mjs and import it works as expected.

Any ideas?

like image 933
Vidar Avatar asked Oct 29 '25 00:10

Vidar


1 Answers

Loaders in Node.js for ECMAScript Modules (ESM) and CommonJS modules. The loader you have defined works with ESM imports, but it doesn't automatically handle CommonJS require calls because they use a different mechanism for module resolution and loading.

If I didn't wan't to use a build tool, I would use Node.js’s require hook mechanism; but it’s more complex and less flexible IMHO.

const Module = require('module');
const fs = require('fs');

Module._extensions['.js'] = function (module, filename) {
  const content = fs.readFileSync(filename, 'utf8');
  const transformedContent = transformContent(content); 
  module._compile(transformedContent, filename);
};

function transformContent(content) {
  // Implement your transpiling logic here
  return content;
}
like image 168
Fergus Avatar answered Oct 31 '25 13:10

Fergus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!