Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Core: Add IS_STORYBOOK global variable #16676

Merged
merged 2 commits into from
Jan 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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