mirror of
https://github.com/storybookjs/storybook.git
synced 2025-04-07 07:21:17 +08:00
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:
parent
744efa64a4
commit
e5ee77a2d1
@ -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
|
||||
}
|
||||
```
|
||||
|
Loading…
x
Reference in New Issue
Block a user