Search code examples
htmlstyled-components

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


index.html

I'm getting the CDN file from:

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

How can I access the styled function?

const {styled} = window.styled-components doesn't work.


Solution

  • styled-components-macro.cjs.min.js is not UMD, so if you include this file you did not get global variable.

    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;
    `
    

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


    UPDATE FROM OP:

    Newer versions has stopped working (probably v5) from the URL above. But it's still working like this on v4:

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