question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

using the cli from another project outside of sanity studio

See original GitHub issue

We have a package that contains services that perform some sanity queries for our app, We would like to use the cli from that app to generate the types from the schema in our sanity studio project.

The sanity studio project and our services project will be in the same parent director so we want to use a relative path for the sanity-codegen.config.ts

something like this

import { SanityCodegenConfig } from 'sanity-codegen';

const config: SanityCodegenConfig = {
  schemaPath: '../../../universal-content/schemas/schema.js',
  outputPath: './schema.ts',

  // NOTE: The CLI ships with a pre-configured babel config that shims out
  // the Sanity parts system. This babel config does not read from any
  // `.babelrc` or `babel.config.js`. You can only configure extra babel
  // options here.
  // babelOptions: require('./.babelrc.json'), // (optional)
};

export default config;

when we run npx sanity-codegen in the services project we get the following error

/home/nirjan/work/digital-media/universal-content/schemas/schema.js:2
import createSchema from "part:@sanity/base/schema-creator";
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:979:16)
    at Module._compile (internal/modules/cjs/loader.js:1027:27)
    at Module._compile (/home/nirjan/work/digital-media/manifold/node_modules/pirates/lib/index.js:99:24)
    at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Object.newLoader [as .js] (/home/nirjan/work/digital-media/manifold/node_modules/pirates/lib/index.js:104:7)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at cli (/home/nirjan/work/digital-media/manifold/node_modules/sanity-codegen/cli.js:73:17)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed.
Exit code: 1
Command: /home/nirjan/.local/share/nvm/v14.15.3/bin/node
Arguments: /usr/share/yarn/lib/cli.js generate:types
Directory: /home/nirjan/work/digital-media/manifold/packages/manifold-services
Output:

info Visit https://yarnpkg.com/en/docs/cli/workspace for documentation about this command.

Do you have any suggestions on how to handle this?

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:1
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
ricokahlercommented, Jan 18, 2021

That error typically occurs as a result of babel not transpiling a file you’re importing.

For some backstory, the most challenging part of creating this lib was figuring out a way to separate sanity schema definitions from everything else we import inside sanity (e.g. components, styles, anything from the parts system). In order to pull those schema definitions, I need to execute the code inside of node.js and that involves transpiling typescript, es modules, and shimming out things codegen doesn’t need to care about.

Long story short, the annoying part of this is configuring babel lol. I ran into the same error because I was importing a symlinked subrepo as part of a monorepo. I fixed it by specifying the babel option ignore.

// this was for my specific setup
import path from 'path';
import { SanityCodegenConfig } from 'sanity-codegen';

const config: SanityCodegenConfig = {
    schemaPath: require.resolve('./schemas'),
    outputPath: path.resolve(__dirname, '../common/schema.ts'),
    prettierResolveConfigPath: require.resolve('@bloomscape/prettier-config'),
    babelOptions: {
        // by default babel ignores everything in node_modules. however, this
        // includes the symlinks yarn creates to enables workspaces.
        // this config un-ignores those symlinks
        ignore: [/node_modules\/(?!@bloomscape).*/],
    },
};

export default config;

I think you might find success by leveraging the same ignore option. I think babel might ignore everything outside of the root by default? (not sure though).

I would try setting ignore to []. This resets the ignore option making it include everything.

import path from 'path';
import { SanityCodegenConfig } from 'sanity-codegen';

const config: SanityCodegenConfig = {
    schemaPath: path.resolve(__dirname, '../../../universal-content/schemas/schema.js'),
    outputPath: path.resolve(__dirname, './schema.ts'),
    babelOptions: {
        ignore: [], // <-- this resets the ignore option (but makes codegen super slow)
    },
};

export default config;

If that fails, I would try seeing what other babel options you can leverage to make it work for you.

This repo uses @babel/register in order to hi-jack require and transpile imports on the fly. There may be some useful information here as well.

0reactions
calebgmahalacommented, Apr 9, 2022

I ran into this issues when running sanity in a separate yarn workspace. I ended up using a similar solution to @ricokahler but instead of skipping all the node_modules with the empty ignore statement, I excluded only node_modules that aren’t used by sanity’s core:

import { SanityCodegenConfig } from 'sanity-codegen'

const config: SanityCodegenConfig = {
  schemaPath: '../studio/schemas/schema.ts',
  outputPath: './schema.ts',
  /**
   * We need to parse the sanity imports inside node modules. This ignore
   * pattern only pulls the packages we need to build the schema file
   */
  babelOptions: {
    ignore: [
      function (filepath) {
        return /\/node_modules\/(?!@sanity)/.test(filepath)
      }
    ]
  }
}

export default config

I know this thread is closed but maybe this helps someone else in the future. The regex may need tweaked depending on what all imports you need access to.

This substantially speeds up the sanity-codegen generation over the empty ignore statement

Read more comments on GitHub >

github_iconTop Results From Across the Web

Command Line Interface (CLI) - Sanity.io
The CLI can be installed as a global dependency in your development environment, locally on a per-project basis, or in many cases, accessed ......
Read more >
Setting up with Sanity CLI
You can use the sanity init command to reinitialize an existing project, which lets you change the project ID, change the dataset, or...
Read more >
CLI API - Sanity.io
The sanity Command Line Interface (CLI) is a handy tool for managing your Sanity projects in your terminal.
Read more >
Hi everyone. I'm new to usingSanity... - Sanity.io community
I'm new to using Sanity and having a bit of an issue with local development ... the other project, logging in and out...
Read more >
5 neat tricks you can make the Sanity CLI do
You can do a couple of things with the sanity documents command, ... Running this in your project folder will give you your...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found