import { Callout } from 'nextra/components';
This is a guide for setting up React Cosmos in a Webpack project.
Install the required packages:
npm i -D react-cosmos react-cosmos-plugin-webpack
Create cosmos.config.json
and enable the Webpack plugin:
{
"plugins": ["react-cosmos-plugin-webpack"]
}
Add cosmos
and cosmos-export
scripts to package.json:
"scripts": {
"cosmos": "cosmos",
"cosmos-export": "cosmos-export",
}
Create a basic fixture at src/Hello.fixture.jsx
:
export default <h1>Hello World!</h1>;
Start React Cosmos:
npm run cosmos
🚀 Open localhost:5000 in your browser.
The Hello
fixture will show up in your Cosmos UI and will render when you select it.
Congratulations 😎
You've taken the first step towards designing reusable components. You're ready to prototype, test and interate on components in isolation.
Cosmos generates a default Webpack config if a custom one isn't provided.
Cosmos compiles your code using dependencies you already installed in your project. Cosmos will auto include common loaders like `babal-loader`, `ts-loader`, `css-loader`, etc. in the default Webpack config. Use a [custom Webpack config](#custom-webpack-config) for more advanced use cases. Make sure `html-webpack-plugin` is installed in your project. You may also need to create a `.babelrc` in your project root.Probably the most common scenario. Most of us end up with a hairy Webpack config sooner or later.
Cosmos picks up webpack.config.js
from the project root automatically. Use the webpack.configPath
setting to provide an existing Webpack config at a different path:
{
"webpack": {
"configPath": "./tools/webpack.config.js"
}
}
Overriding the Webpack config gives you complete control. Use the webpack.overridePath
setting to point to a module that customizes the Webpack config used by Cosmos.
{
"webpack": {
"overridePath": "./webpack.override.js"
}
}
The override function receives a base Webpack config — the default one generated by Cosmos or a custom one loaded from webpack.configPath
. Extend the input config and return the result.
module.exports = (webpackConfig, env) => {
return { ...webpackConfig /* do your thing */ };
};
Cosmos overwrites output.filename
in the Webpack config to [name].js
by default. Due to caching, this isn't ideal when generating static exports via cosmos-export
command. Use the webpack.includeHashInOutputFilename
setting to change the filename template to [name].[contenthash].js
.
{
"webpack": {
"includeHashInOutputFilename": true
}
}