Reproduction repo for a Next.js bug
Exported members that are used in SSR/SSG/ISG page function are undefined on the client (Attempted import error: '..' is not exported from '..' (imported as '..')
).
When you export a member that is used in the page function of getStaticProps
, it will be undefined
on the client.
For example:
// pages/index.tsx
export const revalidateInSeconds = 5 * 60;
export const getStaticProps: GetStaticProps = async () => {
return {
props: {},
revalidate: revalidateInSeconds,
};
};
// components/TestComponent.tsx
import { revalidateInSeconds } from "../pages";
export function TestComponent(): JSX.Element {
console.log("revalidateInSeconds: ", revalidateInSeconds);
return <p>Test component</p>;
}
To make sure that the OS has no play in testing this out, I added a VS Code Docker development container based on Linux (Debian). With that, even if you don't have Linux, the error can be reproduced.
To test this out:
- In VS Code, install the Remote Development extension
- Open the repo in VS Code and start the container (popup at the bottom right or via command palette:
Remote-Containers: Rebuild and Repoen in Container
) - VS Code should restart and be inside the container afterwards
npm i
npm run build
npm run start
- Create Next.js app:
npx create-next-app@latest --use-npm --ts .
- Add
getStaticProps
and aconst
to export:
export const revalidateInSeconds = 5 * 60;
export const getStaticProps: GetStaticProps = async () => {
return {
props: {},
revalidate: revalidateInSeconds,
};
};
- Add a test component that logs the imported
const
(revalidateInSeconds
) and use the component on the page:
// components/TestComponent.tsx
import { revalidateInSeconds } from "../pages";
export function TestComponent(): JSX.Element {
console.log("revalidateInSeconds: ", revalidateInSeconds);
return <p>Test component</p>;
}
// pages/index.ts
...
<main className={styles.main}>
<TestComponent />
<h1 className={styles.title}>
Welcome to <a href="https://nextjs.org">Next.js!</a>
...
- Build & start the app:
npm run build
&npm run start
Click for text!
> next build
info - Checking validity of types
info - Creating an optimized production build
warn - Compiled with warnings
./components/TestComponent.tsx
Attempted import error: 'revalidateInSeconds' is not exported from '../pages' (imported as 'revalidateInSeconds').
Import trace for requested module:
./pages/index.tsx
info - Collecting page data
-
When you run
npm run dev
instead of using the build, you can see that theconsole.log
on the server actually has the value, instead of beingundefined
:Just on the client it is still
undefined
. -
I checked this behavior also for Next.js
v11.1.2
- there, it is not happening. The variable has its value on the client as expected.