Search code examples
reactjstypescriptgatsbystyled-components

Several Instances of 'styled-components' initialized in this application


I've tried all the solutions and now have come to ask this question , I am building a ui component library.

I have two packages , one for library , one for demo , The demo makes use of library using a symlink , file:../ui in its package.json , I build the library first and then consume it in the demo package

The code is available at https://github.com/Qawaz/qal-ui/

I've tried deduping dependencies using npm dedupe but it didn't work. Upon using command npm ls styled-components I get

+-- @paljs/[email protected] -> .\..\ui
| `-- [email protected]
+-- [email protected]
| `-- [email protected] deduped
+-- [email protected]
| `-- [email protected] deduped
`-- [email protected]

Previously I had parent module and workspaces enabled and the two packages were sharing dependencies using npm but I removed that , I migrated to completely separate modules but one module makes a dependency on the other using symlink.

  • styled-components is a peer dependency in the component library not direct
  • version of styled-components is consistent across both projects
  • gatsby is being used , babel plugin for styled components & gatsby plugin for styled components are being used

After adding this to my gatsby-node.js , which is suggested in some answers

const path = require("path")
exports.onCreateWebpackConfig = ({stage, actions}) => {
    actions.setWebpackConfig({
        resolve: {
            alias: {
                "styled-components": path.resolve("node_modules", "styled-components"),
            }
        }
    })
}

I get this error in the console , This error is a false-negative , It goes away if you change something in your gatsby-config and appears at random times

export 'createContentDigest' (imported as 'createContentDigest') was not found in 'gatsby-core-utils/create-content-digest' (module has no exports)

Some answers also suggest this , It causes my build to break

optimization: {
    runtimeChunk: {
        name: "vendor"
    }
}

Solution

  • I found that styled-components just starts complaining if you are using a library with components which also uses styled-components because multiple instances.

    So I switched to emotion, I keep emotion in peer dependencies and the experience is much better, Since emotion contains most features of styled-components and API is very similar.

    There's also goober which provides a setup method, which can be called by the library consumer, goober is a fantastic choice but when I tried to use goober, It didn't contain useTheme hook plus goober is very focused on keeping the bundle smaller while delivering features of css in js.