rsnext/packages/next/build/babel/plugins/next-data.ts

60 lines
1.5 KiB
TypeScript
Raw Normal View History

import { NodePath, PluginObj, types as BabelTypes } from '@babel/core'
2019-04-02 16:09:34 +02:00
2020-05-18 21:24:37 +02:00
export default function ({
types: t,
}: {
types: typeof BabelTypes
}): PluginObj<any> {
2019-04-02 16:09:34 +02:00
return {
visitor: {
ImportDeclaration(path: NodePath<BabelTypes.ImportDeclaration>, state) {
2019-04-02 16:09:34 +02:00
const source = path.node.source.value
if (source !== 'next/data') return
2020-05-18 21:24:37 +02:00
const createHookSpecifier = path.get('specifiers').find((specifier) => {
return (
specifier.isImportSpecifier() &&
specifier.node.imported.name === 'createHook'
)
2019-04-02 16:09:34 +02:00
})
if (!createHookSpecifier) return
const bindingName = createHookSpecifier.node.local.name
const binding = path.scope.getBinding(bindingName)
if (!binding) {
return
}
2020-05-18 21:24:37 +02:00
binding.referencePaths.forEach((refPath) => {
2019-04-02 16:09:34 +02:00
let callExpression = refPath.parentPath
if (!callExpression.isCallExpression()) return
2019-04-02 16:09:34 +02:00
let args: any = callExpression.get('arguments')
2019-04-02 16:09:34 +02:00
if (!args[0]) {
throw callExpression.buildCodeFrameError(
'first argument to createHook should be a function'
)
}
2019-04-02 16:09:34 +02:00
if (!args[1]) {
callExpression.node.arguments.push(t.objectExpression([]))
}
2019-04-02 16:09:34 +02:00
args = callExpression.get('arguments')
args[1].node.properties.push(
t.objectProperty(
t.identifier('key'),
t.stringLiteral(state.opts.key)
)
)
2019-04-02 16:09:34 +02:00
})
},
},
2019-04-02 16:09:34 +02:00
}
}