Skip to content

Instantly share code, notes, and snippets.

@rexxars
Created January 12, 2023 21:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rexxars/0d63e6e385adc78cbdc8b1cb4fd5cfcd to your computer and use it in GitHub Desktop.
Save rexxars/0d63e6e385adc78cbdc8b1cb4fd5cfcd to your computer and use it in GitHub Desktop.
JSCodeShift for Sanity client v5 (default import => named import)
const importName = 'createClient'
v5ClientImport.parser = 'tsx'
module.exports = v5ClientImport
function v5ClientImport(fileInfo, api) {
const j = api.jscodeshift
const root = j(fileInfo.source)
// Imports
// from: import SanityClient from '@sanity/client'
// to: import {createClient as SanityClient} from '@sanity/client'
//
// from: import createClient, {MutationOptions} from '@sanity/client'
// to: import {createClient, MutationOptions} from '@sanity/client'
root
.find(api.jscodeshift.ImportDeclaration, (node) => node.source.value === '@sanity/client')
.filter(
(path) =>
path.node.source.value === '@sanity/client' &&
path.value.specifiers.some((specifier) => specifier.type === 'ImportDefaultSpecifier')
)
.forEach((path) => {
const defaultSpecifier = path.value.specifiers.find(
(specifier) => specifier.type === 'ImportDefaultSpecifier'
)
const namedImports = path.value.specifiers.filter(
(specifier) => specifier !== defaultSpecifier
)
const oldName = defaultSpecifier.local.name
j(path).replaceWith(
j.importDeclaration(
[j.importSpecifier(j.identifier(importName), j.identifier(oldName)), ...namedImports],
j.literal('@sanity/client')
)
)
})
// Requires
// from: const SanityClient = require('@sanity/client')
// to: const {createClient: SanityClient} = require('@sanity/client')
root
.find(j.VariableDeclarator, {
id: {type: 'Identifier'},
init: {callee: {name: 'require'}},
})
.filter((path) => path.value.init.arguments[0].value === '@sanity/client')
.forEach((path) => {
const oldName = path.value.id.name
const prop = j.objectProperty(j.identifier(importName), j.identifier(oldName), false, true)
// Avoid `const {createClient: createClient} = require('@sanity/client')`
if (oldName === importName) {
prop.shorthand = true
}
j(path).replaceWith(
j.variableDeclarator(
j.objectPattern([prop]),
j.callExpression(j.identifier('require'), [j.stringLiteral('@sanity/client')])
)
)
})
return root.toSource()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment