dependents / node-filing-cabinet

Get the file location associated with a dependency/partial's path
MIT License
79 stars 44 forks source link

Add support for .mjs #128

Open amatiasq opened 10 months ago

amatiasq commented 10 months ago

This enables proper dependency parsing for .mjs files.

amatiasq commented 10 months ago

If someone has this issue with madge, I've come up with this snippet to get a hacked version with this change.

Nasty but works.

// This hack is required because filing-cabinet
// (a madge dependency) doesn't support .mjs files
// https://github.com/dependents/node-filing-cabinet/pull/128

import { readFile, writeFile } from 'fs/promises';

async function getHackedMadge() {
    const file = await import.meta.resolve('filing-cabinet/index.js');
    const content = await readFile(file, 'utf8');

    if (!content.includes('.mjs')) {
        const hacked = content.replace(
            "'.jsx': jsLookup,",
            (x) => `${x}\n  '.mjs': jsLookup,`
        );

        await writeFile(file, hacked, 'utf8');
    }

    const module = await import('madge');
    const madge = module.default ?? module.madge;

    // @ts-ignore This is memoization
    getHackedMadge = () => madge;

    return madge;
}

// anywhere else
const madge = await getHackedMadge();
// following invocations are memoized
const madge2 = await getHackedMadge();
console.assert(madge === madge2)
XhmikosR commented 8 months ago

By the same logic, shouldn't .cjs be supported too?

Note that this needs a test case.