ricokahler / sanity-codegen

Generate TypeScript types from your Sanity.io schemas
sanity-codegen-dev.vercel.app
MIT License
270 stars 19 forks source link

Custom input component causes crash when running CLI #256

Open alexandereneroth opened 2 years ago

alexandereneroth commented 2 years ago

Hi, Thanks for this awesome tool!

I've made a simple custom input component(https://www.sanity.io/docs/custom-input-widgets) inside which i import React from 'react'.

This causes the CLI to crash when i run it with the following error:

import React from "react";
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1026:15)
    at Module._compile (node:internal/modules/cjs/loader:1061:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1149:10)

From what i understand after reading other issues(https://github.com/ricokahler/sanity-codegen/issues/57#issuecomment-762031558) this can be solved by editing the babel options inside the sanity-codegen.config.js file.

I have been unsucessful though.

How would i fix it in this case?

jonasbautzmann-the-nu-company commented 2 years ago

Hi,
I found a workaround which solves the issue for me until it is fixed.

I added the babel-plugin-mock-imports to the sanity-codegen.config.js file like that:

const config: SanityCodegenConfig = {
  …
  babelOptions: {
    plugins: [
        [
            "mock-imports",
            {
                redirects: [
                   {
                        pattern: "/path/to/custom/input/component",
                        location: path.resolve(__dirname, "./schema-mock.tsx"),
                    },
                ],
            },
        ]
    ],
  }
}

This plugin will replace all imports which fit the pattern with the schema-mock.tsx:

./schema-mock.tsx

//  inputComponent mock
export default null
kno-raziel commented 2 years ago

hi @jonasbautzmann-the-nu-company , I have tried your workaround but it didnt work for me, can you please provide more info.

image

kno-raziel commented 2 years ago

I ended using the alpha version together with your approach. 🤷

import path from 'path';
import { SanityCodegenConfig } from '@sanity-codegen/cli';

const config: SanityCodegenConfig = {
  schemaPath: './schemas/schema.ts',
  schemaTypesOutputPath: '../schema-types.d.ts',
  babelOptions: {
    plugins: [
      [
        'mock-imports',
        {
          redirects: [
            {
              pattern: 'customComponents',
              location: path.resolve(__dirname, './schema-mock.tsx'),
            },
          ],
        },
      ],
    ],
  },
};

export default config;
jonasbautzmann-the-nu-company commented 2 years ago

Sorry, i forgot to mention that i use the alpha version (1.0.0-alpha.26).