Add FAQ entry about process.env.STORYBOOK

This adds a FAQ entry titled "How can my code detect if it is running in Storybook?". The solution of checking `process.env.STORYBOOK` was recommended by @shilman.

Closes #16343.
This commit is contained in:
Sam Magura 2021-10-16 19:09:22 -04:00
parent 744efa64a4
commit e5ee77a2d1

View File

@ -342,3 +342,32 @@ Out of the box, Storybook provides syntax highlighting for a set of languages (e
</div>
Applying this small change will enable you to add syntax highlight for SCSS or any other language available.
### How can my code detect if it is running in Storybook?
You can do this by checking the value of `process.env.STORYBOOK`, which will
equal `'true'` when running in Storybook. Be careful — `process` may be
undefined when your code runs outside of Storybook.
```javascript
export function isRunningInStorybook() {
try {
if (process.env.STORYBOOK) return true;
} catch {
// A ReferenceError will be thrown if process is undefined
}
return false;
}
```
This works because Babel replaces `process.env.STORYBOOK` with the value of the
`STORYBOOK` environment variable. Because this is done through a Babel plugin,
the following will **NOT** work:
```javascript
export function isRunningInStorybook(): boolean {
return typeof process?.env?.STORYBOOK !== 'undefined';
// ReferenceError: process is not defined
}
```