I maintain a library, written in Typescript and I want to target both CommonJS and ESM. To do this I run the build twice. This requires me to write code (in Typescript) that's valid for both.
One issue is that CommonJS has a __dirname
variable, which I use to load a file relatively. __dirname
doesn't exist in ESM, so I tried to do something like this:
const _mydirname = typeof __dirname !== 'undefined'
? __dirname
: path.dirname(url.fileURLToPath(import.meta.url));
// Example usage
const file = fs.readFileSync(path.join(_mydirname, '../README.md'), 'utf-8')
Unfortunately when building this in Typescript, it emits the following error:
Error: src/application.ts(22,36): error TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'.
Is there a way to do get a path relative to the current script that works in both scenarios?
Cannot use 'import.meta' outside a module
– Stertor