Skip to content

Support loading a config from a openapi-codegen.config.mts file #334

@forivall

Description

@forivall

When i use the mts file extension to define my config as a module, rather than allowing it to be treated as commonjs, the loading doesnt work properly. With npx openapi-codegen -c openapi-codegen.config.mts, i see

Type Error: Cannot read properties of undefined (reading 'source')
    at GenerateCommand.getFromOptions (file:///Users/emily.klassen/code/tmp/oapi-codegen-example/node_modules/@openapi-codegen/cli/lib/cli.js:282:47)
    at Object.task (file:///Users/emily.klassen/code/tmp/oapi-codegen-example/node_modules/@openapi-codegen/cli/lib/cli.js:364:32)
    at xe (file:///Users/emily.klassen/code/tmp/oapi-codegen-example/node_modules/@clack/prompts/dist/index.mjs:79:394)
    at GenerateCommand.execute (file:///Users/emily.klassen/code/tmp/oapi-codegen-example/node_modules/@openapi-codegen/cli/lib/cli.js:359:11)
    at async GenerateCommand.validateAndExecute (file:///Users/emily.klassen/code/tmp/oapi-codegen-example/node_modules/clipanion/lib/advanced/Command.mjs:49:26)
    at async Cli.run (file:///Users/emily.klassen/code/tmp/oapi-codegen-example/node_modules/clipanion/lib/advanced/Cli.mjs:227:24)
    at async Cli.runExit (file:///Users/emily.klassen/code/tmp/oapi-codegen-example/node_modules/clipanion/lib/advanced/Cli.mjs:236:28)

To work around this, i need to change the config like

// openapi-codegen.config.mts
import { defineConfig } from "@openapi-codegen/cli";
import {
  generateSchemaTypes,
  generateReactQueryComponents,
} from "@openapi-codegen/typescript";

export const example = defineConfig({
  example: {
    // can be overridden from cli
    from: {
      source: "github",
      owner: "fabien0102",
      repository: "openapi-codegen",
      ref: "main",
      specPath: "examples/spec.yaml",
    },

    // can be overridden from cli
    outputDir: "src/queries",

    to: async (context) => {
      // You can transform the `context.openAPIDocument` here, can be useful to remove internal routes or fixing some known issues in the specs ;)

      // Generate all the schemas types (components & responses)
      const { schemasFiles } = await generateSchemaTypes(context, {
        /* config */
      });

      // Generate all react-query components
      await generateReactQueryComponents(context, {
        /* config*/
        schemasFiles,
      });
    },
  },
}).example;

The primary motivation for using an mts file is, if i have a tsconfig which uses module: 'node16', the types will not resolve properly, as "@openapi-codegen/cli" et al are esm. Otherwise, i'd have to create another tsconfig specifically to target the config, which is less than ideal.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions