harveyhans

lazy

Home

Adding require() support on ES Modules

Published Oct 01, 2021

I just got this from the official NodeJS documentations page so yeah. I don’t know how to write blogs so I’ll just post the code here:

import { createRequire } from "module";
const require = createRequire(import.meta.url);

const path = require("path");

And now you should be able to require any CommonJS modules even from an ES module (.mjs) or TypeScript. Enjoy!

Source