diff --git a/docs/faq.md b/docs/faq.md index 7669ea6db84e..1932c6fe4d0a 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -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 -} -``` \ No newline at end of file +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`. diff --git a/lib/core-client/src/preview/start.test.ts b/lib/core-client/src/preview/start.test.ts index 1eeaf1461a10..1599bd670602 100644 --- a/lib/core-client/src/preview/start.test.ts +++ b/lib/core-client/src/preview/start.test.ts @@ -1,3 +1,4 @@ +/* global window */ import Events from '@storybook/core-events'; import { @@ -357,6 +358,8 @@ describe('start', () => { }), undefined ); + + expect((window as any).IS_STORYBOOK).toBe(true); }); it('supports forceRerender()', async () => { diff --git a/lib/core-client/src/preview/start.ts b/lib/core-client/src/preview/start.ts index 22b5fba95b87..4cb518bac437 100644 --- a/lib/core-client/src/preview/start.ts +++ b/lib/core-client/src/preview/start.ts @@ -34,6 +34,11 @@ export function start( render?: ArgsStoryFn; } = {} ) { + 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'),