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

Separate SSG Transform from Config (#9639)

* Separate SSG Transform from Config

* update fn name

* fix
parent 96338a76
import { NodePath, PluginObj } from '@babel/core' import { NodePath, PluginObj } from '@babel/core'
import * as BabelTypes from '@babel/types' import * as BabelTypes from '@babel/types'
import { PageConfig } from '../../../types' import { PageConfig } from '../../../types'
const configKeys = new Set(['amp']) const configKeys = new Set(['amp'])
const pageComponentVar = '__NEXT_COMP'
// this value can't be optimized by terser so the shorter the better
const prerenderId = '__NEXT_SPR'
export const EXPORT_NAME_GET_STATIC_PROPS = 'unstable_getStaticProps'
const EXPORT_NAME_GET_STATIC_PATHS = 'unstable_getStaticPaths'
const STRING_LITERAL_DROP_BUNDLE = '__NEXT_DROP_CLIENT_FILE__' const STRING_LITERAL_DROP_BUNDLE = '__NEXT_DROP_CLIENT_FILE__'
// replace program path with just a variable with the drop identifier // replace program path with just a variable with the drop identifier
...@@ -33,18 +27,14 @@ function replaceBundle(path: any, t: typeof BabelTypes) { ...@@ -33,18 +27,14 @@ function replaceBundle(path: any, t: typeof BabelTypes) {
} }
interface ConfigState { interface ConfigState {
isPrerender?: boolean
bundleDropped?: boolean bundleDropped?: boolean
defaultExportUpdated?: boolean
} }
// config to parsing pageConfig for client bundles // config to parsing pageConfig for client bundles
export default function nextPageConfig({ export default function nextPageConfig({
types: t, types: t,
traverse,
}: { }: {
types: typeof BabelTypes types: typeof BabelTypes
traverse: any
}): PluginObj { }): PluginObj {
return { return {
visitor: { visitor: {
...@@ -56,58 +46,13 @@ export default function nextPageConfig({ ...@@ -56,58 +46,13 @@ export default function nextPageConfig({
path: NodePath<BabelTypes.ExportNamedDeclaration>, path: NodePath<BabelTypes.ExportNamedDeclaration>,
state: any state: any
) { ) {
if ( if (state.bundleDropped || !path.node.declaration) {
state.bundleDropped ||
!(path.node.declaration || path.node.specifiers.length)
) {
return
}
if (path.node.specifiers.length) {
const { specifiers } = path.node
specifiers.forEach(specifier => {
if (specifier.type !== 'ExportSpecifier') {
return return
} }
if ( const { declarations } = path.node.declaration as any
specifier.exported.name ===
EXPORT_NAME_GET_STATIC_PROPS ||
specifier.exported.name === EXPORT_NAME_GET_STATIC_PATHS
) {
if (
specifier.exported.name === EXPORT_NAME_GET_STATIC_PROPS
) {
state.isPrerender = true
}
path.node.specifiers = path.node.specifiers.filter(
s => s !== specifier
)
return
}
})
if (path.node.specifiers.length === 0) {
path.remove()
}
return
}
const { declarations, id } = path.node.declaration as any
const config: PageConfig = {} const config: PageConfig = {}
// drop SSR Exports for client bundles
if (
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
}
if (!declarations) { if (!declarations) {
return return
} }
...@@ -144,45 +89,8 @@ export default function nextPageConfig({ ...@@ -144,45 +89,8 @@ export default function nextPageConfig({
}, },
state state
) )
if (!state.bundleDropped && 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()
}
}, },
}, },
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
// babel throws error without
if (prev.type.endsWith('Declaration')) {
prev.type = prev.type.replace(/Declaration$/, 'Expression') as any
}
// @ts-ignore invalid return type
const [pageCompPath] = path.replaceWithMultiple([
t.variableDeclaration('const', [
t.variableDeclarator(t.identifier(pageComponentVar), prev as any),
]),
t.assignmentExpression(
'=',
t.memberExpression(
t.identifier(pageComponentVar),
t.identifier(prerenderId)
),
t.booleanLiteral(true)
),
t.exportDefaultDeclaration(t.identifier(pageComponentVar)),
])
path.scope.registerDeclaration(pageCompPath)
state.defaultExportUpdated = true
},
}, },
} }
} }
import { NodePath, PluginObj } from '@babel/core'
import * as BabelTypes from '@babel/types'
const pageComponentVar = '__NEXT_COMP'
const prerenderId = '__NEXT_SPR'
export const EXPORT_NAME_GET_STATIC_PROPS = 'unstable_getStaticProps'
const EXPORT_NAME_GET_STATIC_PATHS = 'unstable_getStaticPaths'
interface ConfigState {
isPrerender?: boolean
defaultExportUpdated?: boolean
}
export default function nextSsgTransform({
types: t,
traverse,
}: {
types: typeof BabelTypes
traverse: any
}): PluginObj {
return {
visitor: {
Program: {
enter(path, state: ConfigState) {
path.traverse(
{
ExportNamedDeclaration(
path: NodePath<BabelTypes.ExportNamedDeclaration>,
state: any
) {
if (
state.bundleDropped ||
!(path.node.declaration || path.node.specifiers.length)
) {
return
}
if (path.node.specifiers.length) {
const { specifiers } = path.node
specifiers.forEach(specifier => {
if (specifier.type !== 'ExportSpecifier') {
return
}
if (
specifier.exported.name ===
EXPORT_NAME_GET_STATIC_PROPS ||
specifier.exported.name === EXPORT_NAME_GET_STATIC_PATHS
) {
if (
specifier.exported.name === EXPORT_NAME_GET_STATIC_PROPS
) {
state.isPrerender = true
}
path.node.specifiers = path.node.specifiers.filter(
s => s !== specifier
)
return
}
})
if (path.node.specifiers.length === 0) {
path.remove()
}
return
}
const { id } = path.node.declaration as any
if (
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
)
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()
}
},
},
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
// babel throws error without
if (prev.type.endsWith('Declaration')) {
prev.type = prev.type.replace(/Declaration$/, 'Expression') as any
}
// @ts-ignore invalid return type
const [pageCompPath] = path.replaceWithMultiple([
t.variableDeclaration('const', [
t.variableDeclarator(t.identifier(pageComponentVar), prev as any),
]),
t.assignmentExpression(
'=',
t.memberExpression(
t.identifier(pageComponentVar),
t.identifier(prerenderId)
),
t.booleanLiteral(true)
),
t.exportDefaultDeclaration(t.identifier(pageComponentVar)),
])
path.scope.registerDeclaration(pageCompPath)
state.defaultExportUpdated = true
},
},
}
}
import hash from 'string-hash' import hash from 'string-hash'
import { join, basename } from 'path' import { join, basename } from 'path'
import babelLoader from 'babel-loader' import babelLoader from 'babel-loader'
import { EXPORT_NAME_GET_STATIC_PROPS } from '../../babel/plugins/next-page-config' import { EXPORT_NAME_GET_STATIC_PROPS } from '../../babel/plugins/next-ssg-transform'
// increment 'e' to invalidate cache // increment 'e' to invalidate cache
// eslint-disable-next-line no-useless-concat // eslint-disable-next-line no-useless-concat
...@@ -189,6 +189,13 @@ module.exports = babelLoader.custom(babel => { ...@@ -189,6 +189,13 @@ module.exports = babelLoader.custom(babel => {
]) ])
if (isPageFile) { if (isPageFile) {
if (!isServer) {
options.plugins.push([
require.resolve('../../babel/plugins/next-ssg-transform'),
{},
])
}
if (source.includes(EXPORT_NAME_GET_STATIC_PROPS)) { if (source.includes(EXPORT_NAME_GET_STATIC_PROPS)) {
options.plugins.push([ options.plugins.push([
require.resolve( require.resolve(
......
...@@ -10,7 +10,7 @@ const trim = s => ...@@ -10,7 +10,7 @@ const trim = s =>
// avoid generating __source annotations in JSX during testing: // avoid generating __source annotations in JSX during testing:
const NODE_ENV = process.env.NODE_ENV const NODE_ENV = process.env.NODE_ENV
process.env.NODE_ENV = 'production' process.env.NODE_ENV = 'production'
const plugin = require('next/dist/build/babel/plugins/next-page-config') const plugin = require('next/dist/build/babel/plugins/next-ssg-transform')
process.env.NODE_ENV = NODE_ENV process.env.NODE_ENV = NODE_ENV
const babel = (code, esm = true, pluginOptions = {}) => const babel = (code, esm = true, pluginOptions = {}) =>
...@@ -28,7 +28,7 @@ const babel = (code, esm = true, pluginOptions = {}) => ...@@ -28,7 +28,7 @@ const babel = (code, esm = true, pluginOptions = {}) =>
}, },
}).code }).code
describe('babel plugin (next-page-config)', () => { describe('babel plugin (next-ssg-transform)', () => {
describe('getStaticProps support', () => { describe('getStaticProps support', () => {
it('should remove separate named export specifiers', () => { it('should remove separate named export specifiers', () => {
const output = babel(trim` const output = babel(trim`
......
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