dotansimha / graphql-code-generator

A tool for generating code based on a GraphQL schema and GraphQL operations (query/mutation/subscription), with flexible support for custom plugins.
https://the-guild.dev/graphql/codegen/
MIT License
10.83k stars 1.33k forks source link

ESM plugin should be exportable with `export default` #9896

Open mizdra opened 7 months ago

mizdra commented 7 months ago

Is your feature request related to a problem? Please describe.

I want to write a plugin as ESM. But graphql-code-generator cannot load ESM plugin.

// package.json
{
  "name": "playground-graphql-codegen-typescript",
  "type": "module",
  "private": true,
  "scripts": {
    "start": "npm run gen && npm run lint",
    "gen": "graphql-codegen-esm",
    "lint": "tsc"
  },
  "devDependencies": {
    "@graphql-codegen/cli": "^5.0.2",
    "typescript": "^5.4.2"
  },
  "dependencies": {
    "graphql": "^16.8.1"
  }
}
// codegen.ts
import { CodegenConfig } from '@graphql-codegen/cli';

const config: CodegenConfig = {
  schema: './schema.graphql',
  emitLegacyCommonJSImports: false,
  generates: {
    '__generated__/test.txt': {
      plugins: ['./my-plugin.js'],
    },
  },
};

export default config;
// my-plugin.js
/** @type {import('@graphql-codegen/plugin-helpers').CodegenPlugin} */
const plugin = {
  plugin(schema, documents, config) {
    return 'Hi!';
  },
};

export default plugin;
$ npm start

> start
> npm run gen && npm run lint

> gen
> graphql-codegen-esm

✔ Parse Configuration
⚠ Generate outputs
  ❯ Generate to __generated__/test.txt
    ✔ Load GraphQL schemas
    ✔ Load GraphQL documents
    ✖ Invalid Custom Plugin "./my-plugin.js"
      Plugin ./my-plugin.js does not export a valid JS object with "plugin" function.
      Make sure your custom plugin is written in the following form:
      module.exports = {
      plugin: (schema, documents, config) => {
      return 'my-custom-plugin-content';
      },
      };

Describe the solution you'd like

Allow graphql-code-generator to load ESM plugin like CJS plugin.

Describe alternatives you've considered

No response

Is your feature request related to a problem? Please describe.

No response

Workaround

It seems to work if I export the plugin function with named export. However, I think it is better to use the default export.

// my-plugin.js
/** @type {import('@graphql-codegen/plugin-helpers').PluginFunction} */
const plugin = (schema, documents, config) => {
  return 'Hi!';
};

export { plugin };
mizdra commented 7 months ago

Am I understanding this incorrectly? Is it correct behavior that export default is not available?

acomagu commented 4 months ago

Another workaround:

const plugin: CodegenPlugin = {
  plugin(schema, documents, config) { ... },
};

export = plugin;

But I too would prefer to have default export available.(or named export like plugin)