Skip to content

Instantly share code, notes, and snippets.

@PutziSan
Last active February 11, 2020 12:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PutziSan/7621bb69364fcf95409264261b77887c to your computer and use it in GitHub Desktop.
Save PutziSan/7621bb69364fcf95409264261b77887c to your computer and use it in GitHub Desktop.
create-react-story

Create React Story

A npx-utility for creating a storybook-story for your existing react-component.

usage

$ npx https://gist.github.com/PutziSan/7621bb69364fcf95409264261b77887c src/MyComponent.tsx
npx: installed 1 in 6.294s
write new story into src/MyComponent.stories.tsx

This will create the file src/MyComponent.stories.tsx:

// src/MyComponent.stories.tsx
import { storiesOf } from "@storybook/react";
import { MyComponent } from "./MyComponent";

storiesOf("MyComponent", module)
  .add("default", () => {
    return <MyComponent />;
  });

This assumes, your react-component looks like this:

// src/MyComponent.tsx
import * as React from "react";

export function MyComponent() {
  return <div>My Component</div>;
}
#!/usr/bin/env node
const path = require("path");
const fs = require("fs");
function getTemplate(componentName) {
return `import { storiesOf } from "@storybook/react";
import { ${componentName} } from "./${componentName}";
storiesOf("${componentName}", module)
.add("default", () => {
return <${componentName} />;
});
`;
}
const relativePath = process.argv[process.argv.length - 1];
const filePath = path.resolve(path.join(process.cwd(), relativePath));
const dir = path.dirname(filePath);
const extname = path.extname(filePath);
const componentName = path.basename(filePath, extname);
const storyFileName = `${componentName}.stories${extname}`;
const template = getTemplate(componentName);
const newFilePath = path.join(dir, storyFileName);
fs.writeFileSync(newFilePath, template, { encoding: "utf8" });
console.log(`write new story into ${path.relative(process.cwd(), newFilePath)}`);
{
"name": "create-react-story",
"version": "1.0.0",
"description": "creates a story for the given path",
"main": "./index.js",
"bin": "./index.js",
"repository": "https://gist.github.com/PutziSan/7621bb69364fcf95409264261b77887c",
"author": "PS",
"license": "MIT"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment