简体   繁体   English

如何在 Storybook 和 React 中使用全局变量

[英]How to use global variables in Storybook with React

I found this answer, but I am not able to solve the issue with it.我找到了这个答案,但我无法用它解决问题。

The component I trying to load in Storybook depends on a global variable that is injected via a CDN in index.html.我尝试在 Storybook 中加载的组件取决于通过 index.html 中的 CDN 注入的全局变量。

To access the variable in the component I added this comment at the top of the file为了访问组件中的变量,我在文件顶部添加了此注释

/*global <variable name>*/

It's working fine in the React app, but Storybook throwing this error: <variable name> is not defined .它在 React 应用程序中运行良好,但 Storybook 抛出此错误: <variable name> is not defined

I tried adding that comment at the top of the stories.js file and at the top of the config file.我尝试在stories.js文件的顶部和配置文件的顶部添加该注释。 - no luck. - 没运气。

The URL for the CDN is in an env file. CDN 的 URL 位于 env 文件中。 From looking at this doc I tried adding a second script in the HTML file with an env variable that is prepended with STORYBOOK_ .通过查看文档,我尝试在 HTML 文件中添加第二个脚本,其中包含一个以STORYBOOK_的 env 变量。 That didn't work either.那也没有用。

Any ideas on what I can do to get past this?关于我能做些什么来克服这个问题的任何想法?

I've solved this by adding custom head tags: https://storybook.js.org/docs/configurations/add-custom-head-tags/#docs-content我通过添加自定义头部标签解决了这个问题: https : //storybook.js.org/docs/configurations/add-custom-head-tags/#docs-content

Then adding my global variables there, for example:然后在那里添加我的全局变量,例如:

// preview-head.html
<script>
var foo = bar
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM