Are you encountering the Cannot find module './src/temp/config'
error when launching or building
Storybook in a Sitecore JSS project? The console error usually look like this:
PS> npm run storybook
> sxastarter@21.5.0 storybook
> storybook dev -p 6006
@storybook/cli v7.5.3
... Various info and warn logs
=> Failed to build the preview
Error: Cannot find module './src/temp/config'
Require stack:
- .\next.config.js
at Module._resolveFilename (node:internal/modules/cjs/loader:1144:15)
This file is effectively missing sometimes for some of your colleagues or on your computer. This can happen:
-
Just after cloning the repository.
-
Before running the Docker containers for the solution.
What is the Cause of This Error?
The ./src/temp/config.js
file is not committed and is generated by Sitecore JSS. The NPM script responsible
of
generating this file is the bootstrap
script. By inspecting the package.json
scripts, you can
notice that the bootstrap
script is called before running any Next.js command:
"scripts": {
"bootstrap": "ts-node --project tsconfig.scripts.json scripts/bootstrap.ts",
"build": "npm-run-all --serial bootstrap next:build npx tailwindcss -i ./app.css -o ./dist/output.css --watch",
"start:connected": "npm-run-all --serial bootstrap --parallel next:dev start:watch-components",
"start:production": "npm-run-all --serial bootstrap next:build next:start"
},
How to Manually Fix the Error?
To fix this issue with Storybook, we must run that bootstrap
script before running any of the Storybook
NPM
scripts as
well. The manual solution consists of running the npm run bootstrap
command once and then retrying your
Storybook
command. Now that the temporary files are generated, Storybook should build and execute without that error.
There is a Better Way!
While the manual solution works well and needs to be executed only once, it does not help new team members or building and deploying Storybook to Vercel or Netlify.The real solution consists of automatically running the bootstrap
script before running the Storybook
scripts.
Instead of modifying the existing Storybook scripts, I recommend using the pre & post scripts NPM feature
(Thanks to Rob Ahnemann for the tip). That way, when running npm run storybook
, NPM will automatically
run
prestorybook
, storybook
, and poststorybook
in order if those scripts exist.
-
Open your
package.json
file. -
Above or around your existing Storybook scripts, add the following 2 scripts to run before the
storybook
, andbuild-storybook
, scripts:"prestorybook": "npm run bootstrap",
"prebuild-storybook": "npm run bootstrap",The end result should look like this:
"prestorybook": "npm run bootstrap",
"storybook": "storybook dev -p 6006",
"prebuild-storybook": "npm run bootstrap",
"build-storybook": "storybook build" -
Save your file.
Now, every time you, someone on your team, or your deployment scripts want to build or launch Storybook, this will ensure the temporary files are always created first.
Happy Storybooking!