antonk52 / lilconfig

Zero-dependency nodejs config seeker.
MIT License
156 stars 9 forks source link

Feature: Option to return full module export #55

Open shellscape opened 6 hours ago

shellscape commented 6 hours ago

I'd like to request an option to return the full module export, instead of mod.default as specified here: https://github.com/shellscape/lilconfig/blob/e5424adf0944265050b0b8cd1b02d28613682204/src/index.js#L48

I'm working in an environment where named exports are preferred over default exports, and lilconfig currently returns config: undefined for a module which does not have a default export. There is a workaround in using the loaders option to override all of the target file types where a named export is required/preferred. I've pasted my workaround below, which is essentially a copy of the dynamicImport function with a single line change.

While this is functional and within the current API layer of the package, it's not entirely desirable because any changes that are made upstream to the shape of dynamicRequire aren't going to be immediately picked up here in this copy. I believe it would be a minimal change to the code and still within the spirit and default compatibility with cosmiconfig.

Workaround:

const moduleImport = async (id: string) => {
  try {
    const mod = await import(id);
    return mod;
  } catch (e) {
    try {
      return require(id);
    } catch (error) {
      if (
        (error as any).code === 'ERR_REQUIRE_ESM' ||
        (error instanceof SyntaxError &&
          error.toString().includes('Cannot use import statement outside a module'))
      ) {
        throw e;
      }
      throw error;
    }
  }
};

with

    loaders: {
      '.cjs': moduleImport,
      '.js': moduleImport,
      '.mjs': moduleImport
    },
antonk52 commented 3 hours ago

Hi. I am glad that you found a workaround by overriding the default loaders. I think this is an okay workaround currently though having to play catch up is not desired if the implementation changes in the future.

Can you please let me know if the non-default export is something only used within your project or also by other third party tools? I'd like to learn more on how popular this is in practice.

It looks like cosmiconfig also exclusively supports the default exports.