【问题标题】:How can I use styled-components CDN build on browser?如何在浏览器上使用 styled-components CDN 构建?
【发布时间】:2019-11-20 22:29:13
【问题描述】:

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 不起作用。

【问题讨论】:

    标签: html styled-components


    【解决方案1】:

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

    如果您没有使用模块捆绑器或包管理器,我们还有一个托管在 unpkg CDN 上的全局(“UMD”)构建。只需将以下 <script> 标签添加到 HTML 文件的底部:

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

    添加 styled-components 后,您将可以访问全局 window.styled 变量。

    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>
    

    【讨论】:

    • 谢谢!正是我需要的!
    • 我仍然得到 TypeError: window.styled is undefined。请帮忙。
    • @Frumentius 它已停止工作......但我可以确认它以前工作过。可能是一些较新的版本破坏了它。
    • @Frumentius v4 仍然有效。我已经更新了答案。
    【解决方案2】:

    对于版本 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>
    

    【讨论】:

    • 这应该是一个新的公认答案,因为它与人们今天搜索的内容更相关
    猜你喜欢
    • 2021-06-13
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    • 2018-02-13
    • 2017-11-18
    • 1970-01-01
    相关资源
    最近更新 更多