|
|
import type { |
|
|
NodePath, |
|
|
types as BabelTypes, |
|
|
} from 'next/dist/compiled/babel/core' |
|
|
import type { PluginObj } from 'next/dist/compiled/babel/core' |
|
|
|
|
|
const isHook = /^use[A-Z]/ |
|
|
|
|
|
|
|
|
const isBuiltInHook = |
|
|
/^use(Callback|Context|DebugValue|Effect|ImperativeHandle|LayoutEffect|Memo|Reducer|Ref|State)$/ |
|
|
|
|
|
export default function ({ |
|
|
types: t, |
|
|
}: { |
|
|
types: typeof BabelTypes |
|
|
}): PluginObj<any> { |
|
|
const visitor = { |
|
|
CallExpression(path: NodePath<BabelTypes.CallExpression>, state: any) { |
|
|
const onlyBuiltIns = state.opts.onlyBuiltIns |
|
|
|
|
|
|
|
|
const libs = |
|
|
state.opts.lib && |
|
|
(state.opts.lib === true |
|
|
? ['react', 'preact/hooks'] |
|
|
: [].concat(state.opts.lib)) |
|
|
|
|
|
|
|
|
if (!t.isVariableDeclarator(path.parent)) return |
|
|
|
|
|
|
|
|
if (!t.isArrayPattern(path.parent.id)) return |
|
|
|
|
|
|
|
|
const hookName = (path.node.callee as BabelTypes.Identifier).name |
|
|
|
|
|
if (libs) { |
|
|
const binding = path.scope.getBinding(hookName) |
|
|
|
|
|
if (!binding || binding.kind !== 'module') return |
|
|
|
|
|
const specifier = (binding.path.parent as BabelTypes.ImportDeclaration) |
|
|
.source.value |
|
|
|
|
|
if (!libs.some((lib: any) => lib === specifier)) return |
|
|
} |
|
|
|
|
|
|
|
|
if (!(onlyBuiltIns ? isBuiltInHook : isHook).test(hookName)) return |
|
|
|
|
|
path.parent.id = t.objectPattern( |
|
|
path.parent.id.elements.reduce<Array<BabelTypes.ObjectProperty>>( |
|
|
(patterns, element, i) => { |
|
|
if (element === null) { |
|
|
return patterns |
|
|
} |
|
|
|
|
|
return patterns.concat( |
|
|
t.objectProperty( |
|
|
t.numericLiteral(i), |
|
|
|
|
|
element as Exclude< |
|
|
typeof element, |
|
|
BabelTypes.MemberExpression | BabelTypes.TSParameterProperty |
|
|
> |
|
|
) |
|
|
) |
|
|
}, |
|
|
[] |
|
|
) |
|
|
) |
|
|
}, |
|
|
} |
|
|
|
|
|
return { |
|
|
name: 'optimize-hook-destructuring', |
|
|
visitor: { |
|
|
|
|
|
Program(path, state) { |
|
|
path.traverse(visitor, state) |
|
|
}, |
|
|
}, |
|
|
} |
|
|
} |
|
|
|