Skip to content
This repository has been archived by the owner on Mar 26, 2024. It is now read-only.

using 'part:@sanity/form-builder' causes an error #59

Closed
nirjan-dev opened this issue Jan 18, 2021 · 10 comments
Closed

using 'part:@sanity/form-builder' causes an error #59

nirjan-dev opened this issue Jan 18, 2021 · 10 comments

Comments

@nirjan-dev
Copy link

Our app uses a bunch of imports from 'part:@sanity/form-builder' and 'part:@sanity/form-builder/path-event', We are also using a plugin that uses this import.

The cli outputs the following error when using this

Error: Cannot find module 'part:@sanity/form-builder'
Require stack:
- /home/nirjan/work/digital-media/universal-content/node_modules/@cevo/sanity-plugin-tabs/lib/index.js
- /home/nirjan/work/digital-media/universal-content/schemas/documents/category.js
- /home/nirjan/work/digital-media/universal-content/schemas/schema.js
- /home/nirjan/work/digital-media/universal-content/node_modules/sanity-codegen/cli.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:610:15)
    at Function.Module._load (internal/modules/cjs/loader.js:526:27)
    at Module.require (internal/modules/cjs/loader.js:666:19)
    at require (internal/modules/cjs/helpers.js:16:16)
    at Object.<anonymous> (/home/nirjan/work/digital-media/universal-content/node_modules/@cevo/sanity-plugin-tabs/lib/index.js:12:20)
    at Module._compile (internal/modules/cjs/loader.js:759:30)
    at Module._compile (/home/nirjan/work/digital-media/universal-content/node_modules/pirates/lib/index.js:99:24)
    at Module._extensions..js (internal/modules/cjs/loader.js:770:10)
    at Object.newLoader [as .js] (/home/nirjan/work/digital-media/universal-content/node_modules/pirates/lib/index.js:104:7)
    at Module.load (internal/modules/cjs/loader.js:628:32) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/home/nirjan/work/digital-media/universal-content/node_modules/@cevo/sanity-plugin-tabs/lib/index.js',
    '/home/nirjan/work/digital-media/universal-content/schemas/documents/category.js',
    '/home/nirjan/work/digital-media/universal-content/schemas/schema.js',
    '/home/nirjan/work/digital-media/universal-content/node_modules/sanity-codegen/cli.js'
  ]
}
@ricokahler
Copy link
Owner

I'm not sure why this would be occurring. The CLI includes the babel-plugin-module-resolver to resolve anything with part: to a no-op file.

'^part:.*': 'sanity-codegen/no-op',

Can you provide more details about your setup? Are you adding any babel options to the sanity-codegen.config.ts?

@nirjan-dev
Copy link
Author

this is my config

import { SanityCodegenConfig } from "sanity-codegen";

const config: SanityCodegenConfig = {
  schemaPath: "./schemas/schema.js",
  outputPath: "./schema.ts",
  babelOptions: {},
};

export default config;

I'm running npx sanity-codegen from within my sanity studio project directory

@nirjan-dev
Copy link
Author

it looks like this issue comes from using the sanity tabs plugin, we are using a private forked version of the plugin but I've tested it with the original plugin as well and I'm still getting the same error

@ricokahler
Copy link
Owner

ahh i think this is because that plugin imports the form builder inside of its own code while also living in node_moduels. By default, babel register doesn't transpile node_modules so this makes sense to me now.

a potential option is to do ignore: [] making babel transpile everything but that could potentially really slow down codegen.

let me play with this and see if I can get a scalable solution

@ricokahler
Copy link
Owner

Can you try this config?

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

const config: SanityCodegenConfig = {
  schemaPath: './schemas/schema.js',
  outputPath: './schema.ts',
  babelOptions: {
    ...defaultBabelOptions,
    plugins: [
      ...defaultBabelOptions.plugins.filter(
        ([key]) => key !== 'module-resolver'
      ),
      [
        'module-resolver',
        {
          root: ['.'],
          alias: {
            'part:@sanity/base/schema-creator':
              'sanity-codegen/schema-creator-shim',
            'all:part:@sanity/base/schema-type':
              'sanity-codegen/schema-type-shim',
            'part:@sanity/base/schema-type': 'sanity-codegen/schema-type-shim',
            '^part:.*': 'sanity-codegen/no-op',
            '^config:.*': 'sanity-codegen/no-op',
            '^all:part:.*': 'sanity-codegen/no-op',
            // 👇👇👇
            '<forked-package-name>': 'sanity-codegen/no-op',
            // 👆👆👆
          },
        },
      ],
    ],
  },
};

export default config;

replace <forked-package-name> with your forked package name. let me know if that works

@nirjan-dev
Copy link
Author

thank you @ricokahler, It looks like this fixes the issue with the forked sanity-plugin-tabs but still getting the issue with the sanity seo plugin reported here #55

I'm using sanity codegen v0.8.2

@good-idea
Copy link

I'm having the same issue, stemming from a custom input component. Here's the full file contents:

import * as React from 'react';
import { nanoid } from 'nanoid';
import { withDocument } from 'part:@sanity/form-builder';
import { navigate } from '@sanity/default-layout/lib/datastores/urlState';
import { Card, Button } from '@sanity/ui';
import { useDocumentOperation } from '@sanity/react-hooks';
import { client } from '../../utils';

const { useState } = React;

export const AddNewChildArticleInputComponent: React.FC = withDocument(
  ({ document }) => {
    if (!document._id) return null;
    const { patch } = useDocumentOperation(
      document._id.replace(/^drafts\./, ''),
      document._type,
    );
    const [isLoading, setIsLoading] = useState(false);

    const createDocument = (_type: string) => async () => {
      // Create the new article
      const newArticle = await client.create({
        _type,
      });
      // Patch the parent's child articles with the new document
      await patch.execute([
        { setIfMissing: { articles: { articles: [] } } },
        {
          insert: {
            after: 'articles.articles[-1]',
            items: [
              {
                _key: nanoid(),
                _ref: newArticle._id,
                _type: 'reference',
              },
            ],
          },
        },
      ]);
      const newUri = `/intent/edit/id=${newArticle._id}`;
      // Navigate to edit the new document
      navigate(newUri, { replace: false });
    };

    const buttonText = isLoading ? 'Creating...' : 'Create Child Article';

    const buttonStyles = {
      opacity: isLoading ? 0.6 : 1,
      pointerEvents: isLoading ? 'none' : 'auto',
    };
    return (
      <Card style={{ textAlign: 'center' }}>
        <Button
          mode="ghost"
          text="Create Child Article"
          onClick={createDocument('article')}
          style={buttonStyles}
        />
        <Button
          mode="ghost"
          text="Create Article Group"
          onClick={createDocument('articleGroup')}
          style={buttonStyles}
        />
      </Card>
    );
  },
);

I wasn't able to get it to work with custom babel settings, although the package name seems to have changed from when that solution was posted. I've tried:

          alias: {
            'part:@sanity/base/schema-creator':
              '@sanity-codegen/schema-codegen/schema-creator-shim',
            'all:part:@sanity/base/schema-type':
              '@sanity-codegen/schema-codegen/schema-type-shim',
            'part:@sanity/base/schema-type':
              '@sanity-codegen/schema-codegen/schema-type-shim',
            'part:@sanity/base/location':
              '@sanity-codegen/schema-codegen/no-op',
            '^part:.*': '@sanity-codegen/schema-codegen/no-op',
            '^config:.*': '@sanity-codegen/schema-codegen/no-op',
            '^all:part:.*': '@sanity-codegen/schema-codegen/no-op',
          },

But I may be attempting to import from the wrong location.

Regardless, the codegen only fails when trying to parse that input component file - if I comment out the React component (and export a simple no-op component in its place), the codegen succeeds.

Another option for this instance would be to strip out any custom inputComponent properties - if possible - as they don't affect the overall schema.

@scerelli
Copy link

scerelli commented Mar 3, 2022

@good-idea hey mate! i have the same problem, codegen failing cause of a custom component we added in the sanity desk. Could you solve your problem?

import React from 'react'
import {Card, Select} from '@sanity/ui'
import { FormField } from '@sanity/base/components'
import PatchEvent, {set, unset} from '@sanity/form-builder/PatchEvent'
import structure from '@/icons/structure.json'

export const IconSelector = React.forwardRef((props, ref) => {
  const {
    type,
    value,
    readOnly,
    markers,
    presence,
    onFocus,
    onBlur,
    onChange,
  } = props

  const handleChange = React.useCallback(
    (event) => {
      const inputValue = event.currentTarget.value
      onChange(PatchEvent.from(inputValue ? set(inputValue) : unset()))
    },
    [onChange]
  )

  return (
    <FormField
      description={type.description}
      title={type.title}
      __unstable_markers={markers}
      __unstable_presence={presence}
    >
      <Card>
        <Select
          ref={ref}
          readOnly={readOnly}
          value={value}
          onFocus={onFocus}
          onBlur={onBlur}
          onChange={handleChange}
        >
          {Object.values(structure).map((icon) =>  (
            <option key={icon} value={icon}>
              {icon}
            </option>
          ))}
        </Select>
      </Card>
    </FormField>
  )
})

this is the component causing the error

@good-idea
Copy link

I bet it's because of the @/icons/structure.json import at the top?

I do a silly thing:

My directory is set up like:

├── components
│   ├── _inputComponentsMocks
│   │   ├── MetaRegenerator.tsx
│   │   └── index.ts
│   ├── index.ts
│   ├── inputComponents
│   │   ├── MetaRegenerator.tsx
│   │   ├── index.ts
│   └── textStyles.css
├── config
│   └── @sanity
├── constants
├── plugins
├── schemas
│   ├── documents
│   ├── objects
│   ├── shared
│   └── structure
└── utils

My inputComponents/MetaRegenerator.tsx also causes the error. So i have a dummy one in _inputComponentsMocks/MetaRegenerator.tsx that is simply:

import * as React from 'react';

export const MetaRegenerator: React.FC = (props, ref) => {
  return null;
};

Then, I have to bash scripts:

scripts/swapInputComponents.sh

#!/bin/sh

#
# Sanity-codegen breaks when trying to parse the schema because it has a hard
# time resolving modules used within /docs.
# This script swaps it out with a dummy component that won't break the codegen.
#

cd components

mv inputComponents _inputComponents
mv _inputComponentsMocks inputComponents

cd -

scripts/unSwapInputComponents.sh

#!/bin/sh

#
# This script reverses the effects of swapInputComponents.sh
#

cd components

mv inputComponents _inputComponentsMocks
mv _inputComponents inputComponents

cd -

Finally, i call codegen with this command in my package.json:

    "generate-types": "sh scripts/swapInputComponents.sh; yarn sanity-codegen schema-codegen; sh scripts/unSwapInputComponents.sh && yarn prettier ../types/** --write",

(this also applies my prettier settings to the newly generated files but is unrelated)

@alexanderflink
Copy link

I also stumbled upon this problem when using custom input components. Also solved it by using a bash script to temporarily make dummy components. I simply added a DummyComponent.tsx to my components folder.

DummyComponent.tsx

export default function DummyComponent() {
  return null
}

dummy-components.sh

# !/usr/bin/env bash
mv ./src/components ./src/_components
mkdir ./src/components
find ./src/_components -type f -exec basename {} \; | xargs -I{} cp ./src/_components/DummyComponent.tsx "./src/components/{}"

dummy-components-revert.sh

# !/usr/bin/env bash
rm -rf ./src/components
mv ./src/_components ./src/components

package.json

  "scripts": {
    "start": "sanity start",
    "build": "sanity build",
    "build:types": "./dummy-components.sh && npx sanity-codegen schema-codegen && ./dummy-components-revert.sh"
  },

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants