You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Sanity intl插件配置:解决GraphQL无法查询__i18n_lang字段问题

解决方案

方案一:使用Sanity Intl插件自带字段重命名配置

该方案不需要新增额外字段,直接修改插件默认的保留字段名即可解决GraphQL双下划线字段忽略的问题:

  1. 打开项目根目录下的sanity.config.ts(或.js后缀的同类型配置文件),找到plugins数组中的intlInput配置项
  2. 新增fieldNames配置覆盖默认的双下划线开头字段名,参考配置如下:
import { defineConfig } from 'sanity'
import { intlInput } from 'sanity-plugin-intl-input'

export default defineConfig({
  // 项目ID、数据集、插件等基础配置保留原有内容
  plugins: [
    intlInput({
      // 新增以下字段重命名配置
      fieldNames: {
        lang: 'lang', // 将默认的__i18n_lang字段重命名为无下划线的lang
        translations: 'i18n_translations' // 可选:同步修改关联翻译列表字段名避免同样的双下划线问题
      }
    })
  ]
})
  1. 保存配置后重新部署Sanity Studio,再执行sanity graphql deploy命令更新GraphQL端点,之后即可直接查询lang字段获取语言信息。

方案二:新增lang字段自动同步取值

如果不想修改原有插件配置,可以通过自定义字段+自动同步的方式实现需求:

  1. 首先在需要做多语言的文档Schema中新增只读的lang字段,示例如下:
// 对应文档的schema文件,例如/post.js
export default {
  name: 'post',
  title: '文章',
  type: 'document',
  fields: [
    // 原有字段全部保留
    {
      name: 'lang',
      title: '语言',
      type: 'string',
      readOnly: true, // 设为只读避免手动修改导致值不一致
    },
  ]
}
  1. 配置自定义文档操作实现自动同步,每次保存文档时自动将__i18n_lang的取值同步到lang字段:
  • 新建自定义操作文件/actions/syncLangAction.ts,内容如下:
import { DocumentActionProps, useClient } from 'sanity'

export const SyncLangAction = (props: DocumentActionProps) => {
  const client = useClient({ apiVersion: '2023-01-01' })
  const originalHandler = props.onHandle

  return {
    ...props,
    onHandle: async () => {
      const currentDoc = props.draft || props.published
      // 当__i18n_lang有值且lang未赋值/值不一致时同步
      if (currentDoc?.__i18n_lang && currentDoc.lang !== currentDoc.__i18n_lang) {
        await client
          .patch(currentDoc._id)
          .set({ lang: currentDoc.__i18n_lang })
          .commit()
      }
      originalHandler?.()
    },
  }
}
  • 在sanity.config.ts中注册该自定义操作:
export default defineConfig({
  // 其他配置省略
  document: {
    actions: (prevActions) => {
      return prevActions.map((action) => {
        if (action.action === 'publish') {
          return SyncLangAction
        }
        return action
      })
    }
  }
})
  1. 部署Studio后,后续所有文档发布时都会自动同步语言值到lang字段,直接查询该字段即可。

内容的提问来源于stack exchange,提问作者Jozefini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 16:24:06