如何在浏览器上使用样式组件 CDN 构建?

How can I use styled-components CDN build on browser?

index.html

我正在从以下位置获取 CDN 文件:

<script src="https://cdnjs.cloudflare.com/ajax/libs/styled-components/4.3.2/styled-components-macro.cjs.min.js"></script>

如何访问 styled 功能?

const {styled} = window.styled-components 无效。

styled-components-macro.cjs.min.js 不是 UMD,所以如果你包含这个文件,你没有得到全局变量。

If you're not using a module bundler or package manager we also have a global ("UMD") build hosted on the unpkg CDN. Simply add the following <script> tag to the bottom of your HTML file:

<script src="//unpkg.com/styled-components/dist/styled-components.min.js"></script>

Once you've added styled-components you will have access to the global window.styled variable.

const Component = window.styled.div`
  color: red;
`

来源:https://www.styled-components.com/docs/basics#installation


OP 更新:

上面 URL 的较新版本已停止工作(可能是 v5)。但它在 v4 上仍然像这样工作:

<script src="//unpkg.com/styled-components@4.0.1/dist/styled-components.min.js"></script>

对于版本 5,如 docs 中所述,您现在需要在 styled-components

之前包含 react-is
<!-- react, react-dom dev bundles -->
<script crossorigin src="//unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="//unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<!-- react-is -->
<script crossorigin src="//unpkg.com/react-is/umd/react-is.production.min.js"></script>

<!-- styled-components -->
<script crossorigin src="//unpkg.com/styled-components/dist/styled-components.min.js"></script>

<script>
  const Component = window.styled.div`background-color: green;`;
</script>