How to inject a window variable in a storybook?

Member

by lottie , in category: Javascript , 2 months ago

How to inject a window variable in a storybook?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , 2 months ago

@lottie 

To inject a window variable in a Storybook, you can follow these steps:

  1. Create a new file in your Storybook project (e.g., window.js).
  2. In the window.js file, declare and assign the variable you want to inject into the window object. For example, you can do the following:
1
window.myVar = 'Hello, world!';


  1. Import the window.js file in your Storybook configuration file (e.g., .storybook/main.js).
1
2
3
4
5
6
7
8
9
// .storybook/main.js
module.exports = {
  ...
  parameters: {
    window: {
      require: 'path/to/window.js',
    },
  },
};


  1. Once you have done this, the myVar variable will be available in the window object within your Storybook components. You can access it like this:
1
const value = window.myVar; // 'Hello, world!'


By following these steps, you can inject a window variable in your Storybook project and access it within your components.