Search code examples
importdirectoryexportsanity

How to export and import a directory of exported default files in Sanity schema?


Most tutorials and docs I've read utilize a structure like this for the Sanity's schema.js file:

import createSchema from 'part:@sanity/base/schema-creator'
import schemaTypes from 'all:part:@sanity/base/schema-type'

import blog from './documents/blog'
import author from './documents/author'

export default createSchema({
  name: 'default',
  types: schemaTypes.concat([
    blog,
    author,
  ]),
})

but I'd like to import the directory as a single source and I tried:

schema.js:

import createSchema from 'part:@sanity/base/schema-creator'
import schemaTypes from 'all:part:@sanity/base/schema-type'

import * as documents from './documents/'

export default createSchema({
  name: 'default',
  types: schemaTypes.concat([
    documents,
  ]),
})

/documents/index.js:

export { default as author } from './author'
export { default as blog } from './blog'

and I tried:

import author from './author'
import blog from './blog'

export { author, blog }

Bringing all the individual files in schema.js works but when I try to change the file structure to reference one file I get an error of:

<unnamed_type_@_index_1>

from http://localhost:3333/desk/.

Research

In Sanity how can I export all my files within a directory and import them as one line in Sanity's schema?


Solution

  • You can try with this, you'd only have to make one small change:

    /documents/index.js:

    export { default as author } from './author'
    export { default as blog } from './blog
    

    schema.js:

    import createSchema from 'part:@sanity/base/schema-creator'
    import schemaTypes from 'all:part:@sanity/base/schema-type'
    
    import * as documents from './documents'
    
    const allDocuments = Object.values(documents)
    
    export default createSchema({
      name: 'default',
      types: schemaTypes.concat([
        ...allDocuments,
      ]),
    })