Cosmos is a JavaScript DX* tool for designing truly encapsulated React components.
It scans your project for React component fixtures and loads them inside ComponentPlayground, enabling you to:
- Render your components under any combination of props and state
- See component states evolve in real-time as you interact with running instances
Working with ComponentPlayground improves the component design because it surfaces any implicit dependencies. It also forces you to define sane inputs for every component, making them more predictable and easier to debug down the road.
*DX stands for Developer Experience, the counterpart of UX in building a product, system or service.
- You should already be using CommonJS modules to structure your code and webpack to bundle your modules for the browser
- Your React components should be fully encapsulated. They should have no global dependencies and rely exclusively on props for input. Including styles, which means you need to be using style-loader.
- You must create component fixtures for ComponentPlayground to load. The component and fixture files should be nested as in the folder structure below. See the example repo for a better picture.
- Install the Cosmos package through npm
npm install cosmos-js
- Run the ComponentPlayground executable
node_modules/.bin/component-playground
- Open localhost:8989
Running the ComponentPlayground executable will:
- Start a webpack dev server,
serving an instance of ComponentPlayground at
localhost:8989
- Scan the current folder for components and fixtures and feed them to ComponentPlayground
This is the file structure Cosmos expects:
|
+-- components
| +-- FooComponent.jsx
| +-- namespace
| | +-- BarComponent.jsx
+-- fixtures
| +-- FooComponent
| | +-- default.js
| | +-- active.js
| +-- namespace
| | +-- BarComponent
| | +-- default.js
| | +-- paused.js
If the components and fixtures folders are not siblings, their paths can be specified via cli args:
node_modules/.bin/component-playground --components-path src/components --fixtures-path tests/fixtures
The webpack build bundles modules from both the current folder and the Cosmos
package. It is compatible with React classes, ES6 classes, JSX and CSS/LESS
modules out of the box, but you can
customize the webpack config to support additional loaders and settings by
creating a component-playground.config.js
file in the project root. E.g.
module.exports.webpack = function(config) {
config.module.loaders.push(/*...*/);
return config;
};
You can use this functionality to inject external styles or scripts if your components need e.g. Bootstrap to work.
config.entry.push(path.join(process.cwd(), 'injectBootstrapTags.js'));
Cosmos includes React Hot Loader and has webpack's hot module replacement enabled so you can tweak the components and their styles without refreshing the browser:
Explore the Contributing Guide for more information.