Unverified Commit a718df5f authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Rewrite SSG Transform (#9640)

* Rewrite SSG Transform

* Add Named Declaration Support

* more adjustments

* Re-crawl scope
parent b4d0740c
import { NodePath, PluginObj } from '@babel/core' import { PluginObj } from '@babel/core'
import * as BabelTypes from '@babel/types' import * as BabelTypes from '@babel/types'
const pageComponentVar = '__NEXT_COMP' const pageComponentVar = '__NEXT_COMP'
const prerenderId = '__NEXT_SPR' const prerenderId = '__NEXT_SPR'
export const EXPORT_NAME_GET_STATIC_PROPS = 'unstable_getStaticProps'
const EXPORT_NAME_GET_STATIC_PATHS = 'unstable_getStaticPaths'
interface ConfigState { export const EXPORT_NAME_GET_STATIC_PROPS = 'unstable_getStaticProps'
isPrerender?: boolean export const EXPORT_NAME_GET_STATIC_PATHS = 'unstable_getStaticPaths'
defaultExportUpdated?: boolean
}
export default function nextSsgTransform({ export default function nextTransformSsg({
types: t, types: t,
traverse,
}: { }: {
types: typeof BabelTypes types: typeof BabelTypes
traverse: any }): PluginObj<{
}): PluginObj { isPrerender: boolean
done: boolean
}> {
return { return {
visitor: { visitor: {
Program: { Program: {
enter(path, state: ConfigState) { enter(path, state) {
path.traverse( path.traverse({
{ // export function unstable_getStaticPaths() {}
ExportNamedDeclaration( ExportNamedDeclaration(path) {
path: NodePath<BabelTypes.ExportNamedDeclaration>, const declaration = path.node.declaration
state: any if (!declaration) {
) { return
if ( }
state.bundleDropped ||
!(path.node.declaration || path.node.specifiers.length)
) {
return
}
if (path.node.specifiers.length) { if (declaration.type === 'VariableDeclaration') {
const { specifiers } = path.node return
specifiers.forEach(specifier => { }
if (specifier.type !== 'ExportSpecifier') {
return
}
if ( const name =
specifier.exported.name === declaration.type === 'FunctionDeclaration'
EXPORT_NAME_GET_STATIC_PROPS || ? declaration.id && declaration.id.name
specifier.exported.name === EXPORT_NAME_GET_STATIC_PATHS : null
) {
if ( if (name == null) {
specifier.exported.name === EXPORT_NAME_GET_STATIC_PROPS throw new Error(`invariant: null function declaration`)
) { }
state.isPrerender = true
} if (
path.node.specifiers = path.node.specifiers.filter( name === EXPORT_NAME_GET_STATIC_PROPS ||
s => s !== specifier name === EXPORT_NAME_GET_STATIC_PATHS
) ) {
return path.remove()
} state.isPrerender = true
}) }
if (path.node.specifiers.length === 0) { },
path.remove() // export { unstable_getStaticPaths } from '.'
} ExportSpecifier(path) {
return const name = path.node.exported.name
if (
name === EXPORT_NAME_GET_STATIC_PROPS ||
name === EXPORT_NAME_GET_STATIC_PATHS
) {
path.remove()
state.isPrerender = true
if (path.parent.type !== 'ExportNamedDeclaration') {
throw new Error(
`invariant: ${path.type} has unknown parent: ${path.parent.type}`
)
} }
const { id } = path.node.declaration as any if (path.parent.specifiers.length === 0) {
if ( path.parentPath.remove()
id &&
(id.name === EXPORT_NAME_GET_STATIC_PROPS ||
id.name === EXPORT_NAME_GET_STATIC_PATHS)
) {
if (id.name === EXPORT_NAME_GET_STATIC_PROPS) {
state.isPrerender = true
}
path.remove()
return
} }
}, }
}, },
state })
) },
exit(path, state) {
if (state.isPrerender) { if (state.isPrerender) {
// After we delete a bunch of code, we need to re-compute the scope.
// This is necessary for later code elimination.
traverse.cache.clear()
;(path.scope as any).crawl() ;(path.scope as any).crawl()
} }
},
},
ExportDefaultDeclaration(path, state: ConfigState) {
if (!state.isPrerender || state.defaultExportUpdated) {
return
}
const prev = t.cloneDeep(path.node.declaration)
// workaround to allow assigning a ClassDeclaration to a variable path.traverse({
// babel throws error without ExportDefaultDeclaration(path) {
if (prev.type.endsWith('Declaration')) { if (!state.isPrerender || state.done) {
prev.type = prev.type.replace(/Declaration$/, 'Expression') as any return
} }
// @ts-ignore invalid return type state.done = true
const [pageCompPath] = path.replaceWithMultiple([
t.variableDeclaration('const', [ const prev = path.node.declaration
t.variableDeclarator(t.identifier(pageComponentVar), prev as any), if (prev.type.endsWith('Declaration')) {
]), prev.type = prev.type.replace(
t.assignmentExpression( /Declaration$/,
'=', 'Expression'
t.memberExpression( ) as any
t.identifier(pageComponentVar), }
t.identifier(prerenderId)
), // @ts-ignore invalid return type
t.booleanLiteral(true) const [pageCompPath] = path.replaceWithMultiple([
), t.variableDeclaration('const', [
t.exportDefaultDeclaration(t.identifier(pageComponentVar)), t.variableDeclarator(
]) t.identifier(pageComponentVar),
path.scope.registerDeclaration(pageCompPath) prev as any
state.defaultExportUpdated = true ),
]),
t.assignmentExpression(
'=',
t.memberExpression(
t.identifier(pageComponentVar),
t.identifier(prerenderId)
),
t.booleanLiteral(true)
),
t.exportDefaultDeclaration(t.identifier(pageComponentVar)),
])
path.scope.registerDeclaration(pageCompPath)
},
})
},
}, },
}, },
} }
......
...@@ -70,7 +70,7 @@ describe('babel plugin (next-ssg-transform)', () => { ...@@ -70,7 +70,7 @@ describe('babel plugin (next-ssg-transform)', () => {
) )
}) })
it('should remove named export declarations', () => { it('should remove named export function declarations', () => {
const output = babel(trim` const output = babel(trim`
export function unstable_getStaticPaths() { export function unstable_getStaticPaths() {
return [] return []
...@@ -90,7 +90,27 @@ describe('babel plugin (next-ssg-transform)', () => { ...@@ -90,7 +90,27 @@ describe('babel plugin (next-ssg-transform)', () => {
) )
}) })
it('should not remove extra named export declarations', () => { it('should remove named export function declarations (async)', () => {
const output = babel(trim`
export async function unstable_getStaticPaths() {
return []
}
export async function unstable_getStaticProps() {
return { props: {} }
}
export default function Test() {
return <div />
}
`)
expect(output).toMatchInlineSnapshot(
`"const __NEXT_COMP=function Test(){return __jsx(\\"div\\",null);};__NEXT_COMP.__NEXT_SPR=true export default __NEXT_COMP;"`
)
})
it('should not remove extra named export function declarations', () => {
const output = babel(trim` const output = babel(trim`
export function unstable_getStaticProps() { export function unstable_getStaticProps() {
return { props: {} } return { props: {} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment