/single-spa-example-shared-styled-components

single-spa example that has styled-components as a shared dependency

Primary LanguageJavaScript

single-spa example: Shared styled-components

styled-components poses a problem in a single-spa microfrontends implementation because unlike many other libraries, it requires it be a singleton instance. If there is more than one instance, both fail hard. This means that styled-components absolutely must be a shared dependency. This example shows how to accomplish that.

Setup

  • git clone git@github.com:filoxo/single-spa-example-shared-styled-components.git
  • run yarn install and then yarn bootstrap

Running

  • run yarn start
    • root-config runs on port 9000
    • styleguide runs on port 9001
    • navbar runs on port 9002
  • go to http://localhost:9000/

How this was accomplished

  1. Add navbar and styleguide modules to import map (dc53a4d)
  2. Implement styleguide
    1. Install react and styled-components to styleguide (9e799b3)
    2. Add styled-components to Webpack externals (so that it is not bundled) (6f70b10)
      • Why not also include react and single-spa too? Because they are already in the externals array setup by webpack-config-single-spa-react/webpack-config-single-spa respectively so no need to duplicate it here.
    3. Create and export styled components from styleguide (eg. Button) (4603309)
  3. Add styled-components and react-is to importmap (05188d3)
    • Why is react-is necessary? This is because react-is is also dependent on specific versions of React, so it is decoupled from styled-components' dependencies so it can be provided externally and upgraded along with React.
  4. Import and use styleguide components in navbar, eg. import { Button } from '@filoxo/styleguide' (69caa41)
  5. Celebrate good times 🎉

Additional notes

  • These are implemented within the same repo for illustration purposes. In an organizational setting, each of the modules should be in its own repo.
  • While the styleguide uses styled-components, I chose to implement the local styles for navbar using CSS modules to show that applications can be autonomous when choosing which style technologies they'd like to use.
  • How to test applications that consume styleguide components is not ideal, and something that will hopefully change in the future.
    • For strategies on how to test these, see https://stackoverflow.com/a/66328454/2554793
    • ESM support in Jest is planned
    • maybe it would be possible to create a Systemjs module resolver?
    • One solution to testing is to be able to npm install those dependent module but may require a separate build (due to module format support) and can be highly complicated.