Skip to content

Commit

Permalink
Merge pull request #16676 from srmagura/is-storybook
Browse files Browse the repository at this point in the history
Core: Add IS_STORYBOOK global variable
  • Loading branch information
shilman authored Jan 17, 2022
2 parents 8747f9c + 12f44d7 commit 1a99d9d
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 26 deletions.
27 changes: 1 addition & 26 deletions docs/faq.md
Original file line number Diff line number Diff line change
Expand Up @@ -349,29 +349,4 @@ Applying this small change will enable you to add syntax highlight for SCSS or a
### 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() {
return typeof process?.env?.STORYBOOK !== 'undefined';
// ReferenceError: process is not defined
}
```
You can do this by checking for the `IS_STORYBOOK` global variable, which will equal `true` when running in Storybook. The environment variable `process.env.STORYBOOK` is also set to `true`.
3 changes: 3 additions & 0 deletions lib/core-client/src/preview/start.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* global window */
import Events from '@storybook/core-events';

import {
Expand Down Expand Up @@ -357,6 +358,8 @@ describe('start', () => {
}),
undefined
);

expect((window as any).IS_STORYBOOK).toBe(true);
});

it('supports forceRerender()', async () => {
Expand Down
5 changes: 5 additions & 0 deletions lib/core-client/src/preview/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ export function start<TFramework extends AnyFramework>(
render?: ArgsStoryFn<TFramework>;
} = {}
) {
if (globalWindow) {
// To enable user code to detect if it is running in Storybook
globalWindow.IS_STORYBOOK = true;
}

if (FEATURES?.storyStoreV7) {
return {
forceReRender: removedApi('forceReRender'),
Expand Down

0 comments on commit 1a99d9d

Please sign in to comment.