Skip to content

Instantly share code, notes, and snippets.

@jescalan
Created January 13, 2020 15:58
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 jescalan/bd1d8533a8952b228bdcb42d91115516 to your computer and use it in GitHub Desktop.
Save jescalan/bd1d8533a8952b228bdcb42d91115516 to your computer and use it in GitHub Desktop.
A small babel transform to switch `getStaticProps` to `getServerProps` in nextjs
// getStaticProps, which we use as the primary method for data fetching on all our pages,
// runs at build time and generates page data statically. this data is not regenerated
// unless the site is rebuilt, a lot like a static site generator. therefore, it's not
// helpful when you are trying to live preview content changes without rebuilding the entire
// site, even though its great for performance in production.
//
// In order to solve this, we run this script before pushing the preview version of the website,
// which replaces `getStaticProps` with `getServerProps`, a method with the same signature that
// dynamically fetches data fresh on every page load, making it excellent for fast-changing data,
// which is just what we need for a preview environment.
//
// The nextjs team is working on a "next-native" solution to the preview content problem, as
// soon as this is released we will remove this script and shift our code into the native solution.
// The result may look something like returning { props: { foo: 'bar' }, preview: true } from
// getStaticProps.
const babel = require('@babel/core')
const glob = require('glob')
const path = require('path')
const fs = require('fs')
const prettier = require('prettier')
glob(
`${path.join(__dirname, '../pages')}/**/*.+(jsx|tsx)`,
{},
(err, files) => {
if (err) throw err
files.map(file => {
babel.transformFile(file, babelConfig, (err, result) => {
if (err) throw err
fs.writeFile(
file,
prettier.format(result.code, {
parser: file.match(/\.tsx$/) ? 'typescript' : 'babel',
semi: false,
singleQuote: true
}),
'utf8',
() => console.log(`Transformed: ${file}`)
)
})
})
}
)
const babelConfig = {
plugins: [
['@babel/plugin-syntax-typescript', { isTSX: true }],
'@babel/plugin-syntax-jsx',
'@babel/plugin-syntax-dynamic-import',
staticToServerPropsPlugin
]
}
function staticToServerPropsPlugin({ types: t }) {
return {
visitor: {
FunctionDeclaration(_path) {
if (_path.node.id.name === 'unstable_getStaticProps') {
_path.node.id = t.identifier('unstable_getServerProps')
_path.replaceWith(_path)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment