Skip to content

Instantly share code, notes, and snippets.

@DragorWW
Created November 26, 2019 23:28
Show Gist options
  • Save DragorWW/cbf4b6a2d4543cb66552874527c89723 to your computer and use it in GitHub Desktop.
Save DragorWW/cbf4b6a2d4543cb66552874527c89723 to your computer and use it in GitHub Desktop.
Storybook: auto title base on file path
/*
Read the https://storybook.js.org/docs/guides/guide-react/
Configure:
1) open ./storybook/config.js
2) remove configure(require.context('../src', true, /\.stories\.js$/), module);
3) replace with the code below
4) change path prepare in to getTitle function
5) remove in story files export default.title
Example:
src/components/Button/Button.story.tsx - components/Button
*/
function getTitle(filePath) {
return filePath
.replace(/.*src(.*)/, '$1') // remove all before source folder, default absolut path
.replace('.story.tsx', '') // remove story file extension
.split('/')
// Remove duplication in folder and component name
// example: components/Button/Button -> components/Button
.reduce((acc, value) => {
const isDuplicated = acc[acc.length - 1] !== value;
const isEmpty = value !== '';
if (isDuplicated && isEmpty) {
acc.push(value);
}
return acc;
}, [])
.join('/');
}
const loadStory = require.context('../src', true, /\.story\.tsx$/)
const storyMap = new Map();
loadStory.keys().forEach(i => {
const content = loadStory(i);
const defaultExport = content.default || {};
if (!defaultExport.title) {
defaultExport.title = getTitle(i);
}
storyMap.set(i, {
default: defaultExport,
...content
});
});
const loadStoryWitchTitle = (id) => {
return storyMap.get(id);
};
loadStoryWitchTitle.keys = () => {
return [...storyMap.keys()];
};
configure(loadStoryWitchTitle, module);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment