Skip to content
Proyectos

ricokahler/next-plugin-preval

Ver en GitHub

Acerca de

Pre-evaluate async functions during builds and import them like JSON

Herramientas de desarrollo

Cómo se miden estas cifras

Crecimiento de estrellas medido

in 24h
0
in 7 days
+1
in 15 days
+1
in 1 month
Recopilando historial

Cambios netos en períodos que se solapan, no totales diarios. Los datos no disponibles se dejan en blanco. Las estrellas indican interés, no calidad.

README.md

Original

next-plugin-preval

npm Tests

Run async functions at build time and import their JSON results. The plugin uses webpack and declares support for Next.js 9 through 15. CI builds the example with Next.js 15 on webpack.

Quickstart

npm install next-plugin-preval
// next.config.js
const createNextPluginPreval = require('next-plugin-preval/config');

const withNextPluginPreval = createNextPluginPreval();
module.exports = withNextPluginPreval({});
// my-data.preval.js
import preval from 'next-plugin-preval';

async function getData() {
  return { hello: 'world' };
}

export default preval(getData());

Import my-data.preval from your app to use the result:

import data from './my-data.preval';

console.log(data.hello); // world

Why?

The primary mechanism Next.js provides for static data is getStaticProps. Use a build-time import when multiple pages or API routes share the same static data.

  • Site-wide data: Next.js calls getStaticProps when it generates each static page. A .preval module gives several pages a shared import for data such as the site header.
  • Static data for API routes: It can be useful to pre-evaluate data fetches in API routes to speed up response times and offload work from your database. getStaticProps does not work for API routes while next-plugin-preval does.
  • De-duped and code split data: Since next-plugin-preval behaves like importing JSON, you can leverage the optimizations bundlers have for importing standard static assets. This includes standard code-splitting and de-duping.
  • Zero runtime: Preval files don't get sent to the browser, only their outputted JSON.

See the recipes for concrete examples.

Build-time behavior

This works via a webpack loader that takes your code, compiles it, and runs it inside of Node.js.

  • Since this is an optimization at the bundler level, it will not update with Next.js preview mode, during dynamic SSR, or even ISR. Once this data is generated during the initial build, it can't change. It's like importing JSON. See this pattern for a work around.
  • Because this plugin runs code directly in Node.js, code is not executed in the typical Next.js server context. This means certain injections Next.js does at the bundler level will not be available. We try our best to mock this context via require('next'). For most data queries this should be sufficient, however please open an issue if something seems off.

Recipes

Site-wide data: Shared header

// header-data.preval.js
import preval from 'next-plugin-preval';

async function getHeaderData() {
  const headerData = await /* your data fetching function */;

  return headerData;
}

export default preval(getHeaderData());
// header.js
import headerData from './header-data.preval';
const { title } = headerData;

function Header() {
  return <header>{title}</header>;
}

export default Header;

Static data for API routes: Pre-evaluated listings

// products.preval.js (project root)
import preval from 'next-plugin-preval';

async function getProducts() {
  const products = await /* your data fetching function */;

  // create a hash-map for O(1) lookups
  return products.reduce((productsById, product) => {
    productsById[product.id] = product;
    return productsById;
  }, {});
}

export default preval(getProducts());
// /pages/api/products/[id].js
import productsById from '../../../products.preval';

const handler = (req, res) => {
  const { id } = req.query;

  const product = productsById[id];

  if (!product) {
    res.status(404).end();
    return;
  }

  res.json(product);
};

export default handler;

Code-split static data: Loading non-critical data

// states.preval.js
import preval from 'next-plugin-preval';

async function getAvailableStates() {
  const states = await /* your data fetching function */;
  return states;
}

export default preval(getAvailableStates());
// state-picker.js
import { useState, useEffect } from 'react';

function StatePicker({ value, onChange }) {
  const [states, setStates] = useState([]);

  useEffect(() => {
    // ES6 dynamic import
    import('./states.preval').then((response) => setStates(response.default));
  }, []);

  if (!states.length) {
    return <div>Loading…</div>;
  }

  return (
    <select value={value} onChange={onChange}>
      {states.map(({ label, value }) => (
        <option key={value} value={value}>
          {label}
        </option>
      ))}
    </select>
  );
}

Supporting preview mode

As stated in the notes, the result of next-plugin-preval won't change after it leaves the build. However, you can still make preview mode work if you extract your data fetching function and conditionally call it based on preview mode (via context.preview. If preview mode is not active, you can default to the preval file.

// get-data.js

// 1. extract a data fetching function
async function getData() {
  const data = await /* your data fetching function */;
  return data
}
// data.preval.js
import preval from 'next-plugin-preval';
import getData from './getData';

// 2. use that data fetching function in the preval
export default preval(getData());
// /pages/some-page.js
import data from './data.preval';
import getData from './get-data';

export async function getStaticProps(context) {
  // 3. conditionally call the data fetching function defaulting to the prevalled version
  const data = context.preview ? await getData() : data;
  
  return { props: { data } };
}

Related Projects

  • next-data-hooks — creates a pattern to use getStaticProps as React hooks. Great for the site-wide data case when preview mode or ISR is needed.

Explorar proyectos relacionados

Cargando…