Get a list of exported components from javascript libraries

Viewed 20

Is there a (better) way to get the exported components from an installed library from node_modules, given the paths of the files? The only way I can think of is to parse the file, line by line, and look for them.

To give you the context, I am writing an eslint plugin to replace some imported components to a new library, with a new structure. I want, by giving the paths of the indexes (in node_modules folder), the plugin to be able to fetch the exported components and replace everything by itself. I believe this was done before but I can not find a good solution.

1 Answers

Why don't you change imports of your library instead? It looks like a hack to patch files in node_modules. If you need some other exports you can write a new library that will re-export only what you need. Also the idea you want to implement makes harder with constructions like this:

export * from './api.js';

You need to walk all the exports in all files.

If you work with CommonJS, it can dynamically export things:

buildSomeApiExports();

function buildSomeExports() {
    module.exports = {};
}

And this code is correct, and dew to it's dynamic nature this is really hard task to do for statical analysis of ESLint plugin.

In case you will work with imports of your application, you can use Putout code transformer I'm working on, it can look this way:

export const replace = () => ({
    'import {old} from "old-library"': 'import {newOne} from "new-library"',
});

This is Replacer but you can get more sophisticated examples with other plugin types.

Related