Running scripts at build-time with Next.js

Viewed 2392

I was wondering what the recommended way is to run a script that generates some static XML files at build time. Ideally, those scripts should be ES Modules so code can be shared between those scripts and my Next / React application code.

I think I need to customize the Webpack config but I'm not sure how I can run code there that uses ES Modules (and not just uses require).

EDIT: I have something like this in mind, which should also work with Modules:

{
  webpack: (config, { isServer }) => {
  if (isServer) {
    require('./scripts/generate-xml');
  }

  return config;
}
2 Answers

It would be helpful if you could be more descriptive but from what I understand you need to run a particular script at Build-time for your NextJS app. You can make use of the getStaticProps() function provided by NextJS.


// your NextJS page

function Mypage() {
  return (
    <div></div>
  )
}

// This is the function you need
export async function getStaticProps() {
// do anything you want to do at build-time
// A good way would be to call a function by importing and the function will be executed at runtime. 
}

You can see more detail at official docs - https://nextjs.org/docs/basic-features/data-fetching#typescript-use-getstaticprops

On another note, If you want to generate XML for SEO reasons at Build time, a better way would be by using API routes and feeding that API route as your XML file location inside robot.txt. See this - https://github.com/toughyear/blog/blob/master/pages/api/posts-sitemap.js

if you use a custom babel.config.js, you can use babel macros, but this will opt out from SWC in Nextjs 12. I am searching for an alternative to be compatible with SWC. For now the only workaround is to have a "pre-build" script.

You can wrap your npm run start script to run anything you want before calling next build

Related