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.
git clone git@github.com:filoxo/single-spa-example-shared-styled-components.git
- run
yarn install
and thenyarn bootstrap
- run
yarn start
- root-config runs on port 9000
- styleguide runs on port 9001
- navbar runs on port 9002
- go to http://localhost:9000/
- Add
navbar
andstyleguide
modules to import map (dc53a4d) - Implement
styleguide
- Install
react
andstyled-components
to styleguide (9e799b3) - Add
styled-components
to Webpack externals (so that it is not bundled) (6f70b10)- Why not also include
react
andsingle-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.
- Why not also include
- Create and export styled components from styleguide (eg.
Button
) (4603309)
- Install
- Add
styled-components
andreact-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.
- Why is
- Import and use styleguide components in navbar, eg.
import { Button } from '@filoxo/styleguide'
(69caa41) - Celebrate good times 🎉
- 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.