reactjsnpmnext.jsstyled-componentsnpm-publish

Published styled-components react library does not have access to user app ThemeProvider


So i'm building a design system for this company and the component system is displayed correctly in the design system storybook. But when I import it in the consumer app I get the following error

TypeError: Cannot read property 'width' of undefined in theme.border.width

Design System project:

/// src/components/Button/index.js
import { Wrapper } from './styles'
import React from 'react'

export const Button = (props) => (
  <Wrapper {...props}>
    {children}
  </Wrapper>
)

.

///src/components/Button/styles.js    
export const Wrapper = styled.button`
...
border-width: ${({theme}) => theme.border.width};
...
`

.

/// .storybook/preview.js
import React from 'react'
import { ThemeProvider } from 'styled-components'
import { GlobalStyle } from '../src/styles/globalStyles'
import { theme } from '../src/styles/theme'

export const parameters = {
  actions: { argTypesRegex: '^on[A-Z].*' }
}
export const decorators = [
  Story => (
      <ThemeProvider theme={theme}>
        <GlobalStyle />
        <Story />
      </ThemeProvider>
    )
 ]

.

/// src/index.js
...
export { Button } from 'components/Button'
export { theme } from 'style/theme'

...

.

/// babel.config.js
module.exports = {
  presets: [
    [
      '@babel/env',
      {
        modules: false
      }
    ],
    ['@babel/preset-react']
  ],
  plugins: [
    [
      'styled-components',
      {
        ssr: true,
        displayName: true,
        preprocess: false,
        minify: false
      }
    ]
  ]
}

.

///rollup.config.js
import babel from 'rollup-plugin-babel'
import includePaths from 'rollup-plugin-includepaths'
import peerDepsExternal from 'rollup-plugin-peer-deps-external'

export default [
  {
    input: 'src/index.js',
    output: [
      {
        name: 'rollup-tutorial',
        file: 'dist/index.js',
        format: 'es'
      }
    ],
    plugins: [
      babel({
        exclude: 'node_modules/**'
      }),
      includePaths({
        paths: ['src'],
        extensions: ['.js', '.json', '.html']
      }),
      peerDepsExternal()
    ]
  }
]

.

/// package.json
{
  "name": "design-system",
  "main": "dist/index.js"
  "files: ["dist"],
  "scripts": {
    ...
    "build": "rollup --config"
    ...
  },
  "devDependencies": {
    "@babel/core": "^7.12.10",
    "@babel/preset-react": "^7.12.10",
    "@babel/preset-env": "^7.12.13",
    "react": "17.0.1",
    "react-dom": "17.0.1",
    "rollup": "^2.38.4",
    "rollup-plugin-babel": "^4.4.0",
    "rollup-plugin-includepaths": "^0.2.4",
    "rollup-plugin-peer-deps-external": "^2.2.4",
    "styled-components": "^5.2.1",
  },
 "peerDependencies": {
    "prop-types": ">= 15.x.x",
    "react": ">= 17.x.x",
    "styled-components": ">= 5.x.x",
  }
}

App consumer NextJs default config

/// .babelrc

{
  "presets": ["next/babel"],
  "env": {
    "development": {
      "plugins": [
        [
          "styled-components",
          {
            "ssr": true,
            "displayName": true
          }
        ]
      ]
    },
    "production": {
      "presets": [
        "next/babel"
      ],
      "plugins": [
        [
          "styled-components",
          {
            "ssr": true,
            "displayName": false
          }
        ]
      ]
    }
  }
}

.

///package.json
{
  ...
  "dependencies":  {
    ...
    "design-system": "../design-system/",
    ...
  }
  ...
}

.

/// pages/_app.js
import { ThemeProvider } from 'styled-components'
import { theme } from 'design-system'

function MyApp({ Component, pageProps }) {
  console.log(theme)
  return (
    <ThemeProvider theme={theme}>
      <Component {...pageProps} />
    </ThemeProvider>
  )
}

.

///pages/index.js
import { Button } 'design-system'

export default function Home() {
  return (
   <Button />
  )
}

Note:

The console.log(theme) prints the expected theme however the button doesnt have access to the theme provided by styled-components. I guess i'm missing some important configurantion in babel rollup or something

Note 2:

I already tried wrapping up the components in withComponent HOC the only working solution was the next piece of code

///pages/index.js
import { Button } 'design-system'
import { useTheme } 'styled-components'

export default function Home() {
  const theme = useTheme()
  return (
   <Button theme={theme} />
  )
}

But this loses the whole point of using context

Thanks in advance


Solution

  • I've had a similar issue when developing a component library using storybook and emotion/styled-components. The issue was that I was using the styled-components' ThemeProvider from the consumer app, as you did in your _app.js. The solution was to create and export a custom ThemeProvider on the component library, using the library's styled-component package, like so:

    import { ThemeProvider } from 'styled-components'
    import { theme as defaultTheme } from '../src/styles/theme'
    
    const CustomThemeProvider = ({ theme = defaultTheme, children }) => (
      <ThemeProvider theme={theme}>
        {children}
      </ThemeProvider>
    )
    
    export { CustomThemeProvider }
    

    and then use in your consumer app

    /// pages/_app.js
    import { CustomThemeProvider, theme } from 'design-system'
    
    function MyApp({ Component, pageProps }) {
      console.log(theme)
      return (
        <CustomThemeProvider theme={theme}>
          <Component {...pageProps} />
        </CustomThemeProvider>
      )
    }