LoginSignup
31
26

More than 5 years have passed since last update.

Storybook for vue.js ドキュメント 日本語翻訳

Last updated at Posted at 2018-06-18

Storybook

Storybook を Vue.js で使っていきたいので、必要な箇所を翻訳します。

Introduction

Storybook is a UI development environment for your UI components. With it, you can visualize different states of your UI components and develop them interactively.

Storybook は UI Component のための開発環境です。これによって様々な状態の UI Component を視覚化し、インタラクティブな開発を可能にします。

Storybook runs outside of your app. So you can develop UI components in isolation without worrying about app specific dependencies and requirements.

Storybook はメインのアプリケーションとは別の環境で実行されます。そのため UI Component を独立して開発することができるようになり、その結果、アプリケーション特有の依存性や必要条件について考える必要がなくなります。

Storybook also comes with a lot of addons and a great API to customize as you wish. You can also build a static version of your storybook and deploy it anywhere you want.

またストリーブックにはたくさんのアドオンがあります。さらに、優れた API によって望むようにカスタマイズすることもできます。Storybook を static なバージョンで構築しそれを望む場所にデプロイすることもできます。

Here are some featured storybooks that you can reference to see how Storybook works:

  • Demo of React Dates - source
  • Demo of React Native Web - source

以下に紹介する Storybook で、Storybook がどのように機能するのか確認することができます。

Storybook for Vue

You may have tried to use our quick start guide to setup your project for Storybook. If you want to set up Storybook manually, this is the guide for you.

すでにクイックスタートガイドを参照して Storybook のプロジェクトを設定していただいたことかと思います。このガイドは、それとは違って、一から設定していくためのものです。

This will also help you understand how Storybook works.

またこのガイドを通じて、Storybook がどのように機能してるかもご理解いただけるでしょう。

Starter Guide Vue

Storybook has its own Webpack setup and a dev server.
The Webpack setup is very similar to Vue CLI’s, but allows you to configure it however you want.

Storybook は自分自身ための Webpack setup と dev server を持ちます。Webpack の設定は、Vue CLI のものとほとんど同じですが、望むように変更することもできます。

In this guide, we are trying to set up Storybook for your Vue project.

本ガイドでは、Vue プロジェクトのための Storybook を設定していきましょう。

Table of contents

  • Add @storybook/vue
  • Add vue and babel-core
  • Create the NPM script
  • Create the config file
  • Write your stories
  • Run your Storybook

Add @storybook/vue

First of all, you need to add @storybook/vue to your project. To do that, simply run:

まずは @storybook/vue をプロジェクトに追加しましよう。そのためには以下を実行します。

npm i --save-dev @storybook/vue

Add vue and babel-core

Make sure that you have vue and babel-core in your dependencies as well because we list is as a peerDependency:

vue と babel-core も追加します。

npm i --save vue
npm i --save-dev babel-core

Create the NPM script

Add the following NPM script to your package.json in order to start the storybook later in this guide:

以下の NPM script を package.json に追加して、後ほど storybook を開始できるようにしておきます。

{
  "scripts": {
    "storybook": "start-storybook -p 9001 -c .storybook"
  }
}

Create the config file

Storybook can be configured in several different ways. That’s why we need a config directory. We’ve added a -c option to the above NPM script mentioning .storybook as the config directory.

Storybook を設定する方法はいくつかあります。設定をするためには config のためのディレクトリが必要です。先ほど NPM スクリプトで -c オプションを記述し .storybook を参照したのは、config ディレクトリを指定するためです。

There are 3 things you need to tell Storybook to do:

Storybook に対して config によって指定すべきことは 3 つあります。

  • Import and globally register with Vue.component() any global custom components just like you did with your project. (Note: components registered locally will be brought in automatically).
  • For any required Vue plugins (e.g. vuex), you’ll also need to install these with Vue.use.
  • Require your stories.
  • Component を import し、Vue.component() を使って Global に登録します。これは通常の Vue プロジェクトでおこなっていることと同様の手順です。(訳注: Note の中身が正確にわからないが、Local に登録しても Storybook の場合は勝手にグローバルに登録されるのと同じ挙動になるということか?)
  • 必要な Vue plugin (例えば Vuex など) がある場合には、これも Vue.use() で install しましょう。
  • 自分で書いた Story を require します。

Here’s an example .storybook/config.js to get you started:

ではサンプルをみてみましょう。

.storybook/config.js

import { configure } from '@storybook/vue';

import Vue from 'vue';
import Vuex from 'vuex'; // Vue plugins をインポートします

// Import your custom components.
// Custom Component を import します。
import Mybutton from '../src/stories/Button.vue';

// Install Vue plugins.
// Vue plugin をインストールします。
Vue.use(Vuex);

// Register custom components.
// Custom Component を登録します。
Vue.component('my-button', Mybutton);

function loadStories() {
  // 必要な Story を require します。
  // You can require as many stories as you need.
  require('../src/stories');
}

configure(loadStories, module);

This example registered your custom Button.vue component, installed the Vuex plugin, and loaded your Storybook stories defined in ../stories/index.js.

Button.vue というカスタムコンポーネントを登録し、Vue plugin をインストールし、../stories/index.js に定義した Story をロードしています。

All custom components and Vue plugins should be registered before calling configure().

全てのカスタムコンポーネントと Vue プラグインは、configure()を呼び出す前に登録するようにしてください。

This stories folder is just an example, you can load stories from wherever you want to. We think stories are best located close to the source files.

この story フォルダーの位置は一つのサンプルであって、どこでも好きな場所に配置することができます。一番良いのは source file の近くに配置することだと考えています。

Write your stories

Now you can write some stories inside the ../stories/index.js file, like this:

これで story を ../stories/index.js に書いていく準備ができました。例えばつぎのようにしてみましょう。


import Vue from 'vue';

import { storiesOf } from '@storybook/vue';

import MyButton from './Button.vue';

storiesOf('MyButton', module)
  .add('story as a template', () => '<my-button :rounded="true">story as a function template</my-button>')
  .add('story as a component', () => ({
    components: { MyButton },
    template: '<my-button :rounded="true">rounded</my-button>'
  }));

Each story is a single state of your component. In the above case, there are two stories for the MyButton component:

それぞれの story は、それぞれことなった状態のコンポーネントが記述されています。上記のケースであれば、MyButton コンポーネントの 2 つの状態 = 2 つの story が記述されています。

  • story as a template
  • story as a component

Run your Storybook

Now everything is ready. Simply run your storybook with:
これで全てが準備されました。では次のコマンドで storybook を動かしましょう。

npm run storybook

Now you can change components and write stories whenever you need to. You’ll get those changes into Storybook in a snap with the help of Webpack’s HMR API.

コンポーネントを変更したり、story を書いたりすることができるようになりました。これらの変更は Webpack の HMR API のおかげで、すぐに反映されます。

Writing Stories

Storybook is all about writing stories. Usually a story contains a single state of one of your components. That’s like a visual test case.

Storybook でできることは、story を書くことです。Story は通常ある一つの状態のコンポーネントを含みます。Visual Test の場合と似ています。

Technically, a story is a function that returns a React element.

技術的には、story は React element を返す関数です。

You can write a set of stories for your components and you’ll get a storybook.

コンポーネントのためのストーリー一式を書くことで、ストーリーブックが作成されます。

Keeping your stories

There’s no hard and fast rule for this. But, keeping stories close to your components is a good idea.

Story をどこに配置させるのかということについて鉄則のようなものはありません。しかし、Component があるディレクトリの近くに置くほうがいいのではないかなと思います。

For example, let’s say your UI components live in a directory called: src/components. Then you can write stories inside the src/stories directory.

例えば UI Component が src/components にある場合には、src/stories ディレクトリに配置したほうがいいでしょう。

This is just one way to do that. You can always edit your storybook config file and ask it to load stories from anywhere you want.

これは一つの提案にすぎません。どこにファイルをおいてもかまいません。

Writing stories

This is how you write stories: (Let’s assume there’s a component called “Button” in src/components/Button.js.)

では story を書く方法について話を進めます。(Button という名前のコンポーネントが src/components/Button.js にある前提で話を進めていきます。)

// file: src/stories/index.js

import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import Button from '../components/Button';

storiesOf('Button', module)
  .add('with text', () => (
    <Button onClick={action('clicked')}>Hello Button</Button>
  ))
  .add('with some emoji', () => (
    <Button onClick={action('clicked')}><span role="img" aria-label="so cool">😀 😎 👍 💯</span></Button>
  ));

This will show stories in your storybook like this:
するとストーリーブックには次のように表示されるはずです。

This is just our core API for writing stories. In addition to this, you can use the official and third party Storybook addons to get more functionality.

今使ったのが Story を書くために必要な core となる API です。これに加えて、公式とサードパーティーの addon を使うことで、より機能的にすることもできます。

Loading stories dynamically

Sometimes, you will want to load your stories dynamically rather than explicitly requiring them in the Storybook config file.

Story を読み込む際に、storybook の設定ファイルの中で明示的にファイル名を指定するのではなく、動的に読み込みたい場合があると思います。

For example, you may write stories for your app inside the src/components directory with the .stories.js extension. Then you will want to load them at once. Simply edit your config directory at .storybook/config.js as follows:

例えば、src/components ディレクトリの中に .stories.js という拡張子で story 用のファイルがあるとしましょう。そしてこれをいっぺんにロードしたいとします。その場合はコンフィグ用のディレクトにある .storybook/config.js を以下のように編集しましょう。

import { configure } from '@storybook/react';

const req = require.context('../src/components', true, /\.stories\.js$/)

function loadStories() {
  req.keys().forEach((filename) => req(filename))
}

configure(loadStories, module);

Here we use Webpack’s require.context to load modules dynamically. Have a look at the relevant Webpack docs to learn more about how to use require.context.

ここでは Webpack の require.context を用いて動的に module をロードしています。これについてより学習したい場合には Webpack の公式ドキュメントをみてください。(https://webpack.js.org/guides/dependency-management/#require-context)

The React Native packager resolves all the imports at build-time, so it’s not possible to load modules dynamically. If you don’t want to import all your stories manually you can use react-native-storybook-loader to automatically create the import statements for all of your stories.

React Native の packager は、全ての import を build する際に解決しています。そのため、動的にモジュールを読み込むことはできません。手動で全ての story を import したくない場合には、react-native-storybook-loader を使って自動的に全ての story を読み込むための宣言を作成するようにしてください。

Using Decorators

A decorator is a way to wrap a story with a common set of component(s). Let’s say you want to center all your stories. Here is how we can do this with a decorator:

decorator は、story を共通のコンポーネント(単一もしくは複数、どちらでも可能です)で wrap するための手法です。全てのストーリーをセンターに配置したいとしましょう。decorator がそういう時に役立ちます。

import React from 'react';
import { storiesOf } from '@storybook/react';
import MyComponent from '../my_component';

storiesOf('MyComponent', module)
  .addDecorator(story => (
    <div style={{textAlign: 'center'}}>
      {story()}
    </div>
  ))
  .add('without props', () => <MyComponent />)
  .add('with some props', () => <MyComponent text="The Comp"/>);

上記の例は、decorator をこの一連のストーリーだけに加えています。(この例でいえば、MyComponent ストーリーグループにだけに decorator が適用されています。)

But, you can also add a decorator globally and it’ll be applied to all the stories you create. This is how to add a decorator like that:

反対に、decorator をグローバルに加えて、全ての story に追加することもできます。以下のように書きます。

import React from 'react';
import { configure, addDecorator } from '@storybook/react';

addDecorator(story => (
  <div style={{textAlign: 'center'}}>
    {story()}
  </div>
));

configure(function () {
  // ...
}, module);

Using Markdown

Markdown を使うこともできます。

Nesting stories

You can organize your stories in a nesting structures using ”/” as a separator:

story を体系的に構成するために、"/" を用いてセパレイトすることで、ネストさせることができます。

// file: src/stories/index.js

import React from 'react';
import { storiesOf } from '@storybook/react';
import Button from '../components/Button';

storiesOf('My App/Buttons/Simple', module)
  .add('with text', () => (
    <Button onClick={action('clicked')}>Hello Button</Button>
  ));

storiesOf('My App/Buttons/Emoji', module)
  .add('with some emoji', () => (
    <Button onClick={action('clicked')}><span role="img" aria-label="so cool">😀 😎 👍 💯</span></Button>
  ));

Generating nesting path based on __dirname

The name is just a javascript string, by using a template literal, you can easily interpolate data.

story の名前を定義する部分は単なる JavaScript の文字列なので、template literal を用いることで、簡単に data を挟み込むことができます。

One example would be to use base from paths.macro:

base from paths.macro を用いた例は以下のようになるでしょう。

import React from 'react';
import base from 'paths.macro';

import { storiesOf } from '@storybook/react';

import BaseButton from '../components/BaseButton';

storiesOf(`Other|${base}/Dirname Example`, module)
  .add('story 1', () => <BaseButton label="Story 1" />)
  .add('story 2', () => <BaseButton label="Story 2" />);

This uses babel-plugin-macros.

babel-plugin-macros を用いています。

Run multiple storybooks

You can run multiple storybooks for different kinds of stories (or components). To do that, you can create different NPM scripts to start different stories. See:

異なる内容を持った複数の storybook を同時に走らせることも可能です。そのためには NPM Script を追加して、異なる story を開始できるようにします。次の通りです。

{
   "scripts": {
     "start-storybook-for-theme": "start-storybook -p 9001 -c .storybook-theme",
     "start-storybook-for-app": "start-storybook -p 8001 -c .storybook-app"
   }
}

Exporting Storybook as a Static App

Storybook gives a great developer experience with its dev time features, like instance change updates via Webpack’s HMR.

Storybook は開発時にとても素晴らしい体験を与えてくれます。例えば Webpack の HMR を使った、即時的な変更の反映などです。

But Storybook is also a tool you can use to showcase your components to others. Demos of React Native Web and React Dates are a good example for that.

ですがコンポーネントを誰かに見せる際にも、Storybook は役に立ちます。Demos of React Native Web and React Dates の例をご覧ください。

For that, Storybook comes with a tool to export your storybook into a static web app. Then you can deploy it to GitHub pages or any static hosting service.

Storybook は storybook を static なウェブアプリケーションとして書き出す機能を持っています。書き出した static なウェブアプリケーションを Github pages や、そのほかの static なアプリケーションをホストできるサービスにデプロイすることができます。

Simply add the following NPM script:

そのためには次のようにします。

{
  "scripts": {
    "storybook": "build-storybook -c .storybook -o .out"
  }
}

Then run npm run storybook.

それから npm run storybook を実行します。

This will build the storybook configured in the Storybook directory into a static webpack and place it inside the .out directory. Now you can deploy the content in the .out directory wherever you want.

これによって Storybook ディレクトリの設定によって指定された storybook を static な webpack によって処理して、その結果が .out ディレクトリに出力されます。その .out ディレクトリに出力されたコンテンツを、望む場所にデプロイすることができますね。

To test it locally, simply run the following commands:

ローカルでテストするには、次のコマンドを実行してください。

cd .out
python -m SimpleHTTPServer

Custom Webpack Config

Default mode

The default Webpack config of Storybook is balanced for a medium-size project (specially created with Create React App) or a library. But if you already have your own Webpack setup, that’s not useable.

Storybook の default の webpack の設定は、中規模プロジェクト(とくに Create React App で作られたプロジェクト) にちょうどいいものとなっています。しかし既にご自身の webpack の setup があるのであれば、デフォルトの設定は必要ないでしょう。

That’s why we allow you to customize our Webpack setup by providing a webpack.config.js file exporting a webpack 2 compatible config exported as a commonjs module.

そこで Storybook は webpack の設定をカスタマイズすることができるようになっています。これは webpack.congfig.js という名前のファイルで、かつ webpack2 準拠の記法で書かれた commjs module を export したもので設定することができます。

There are a few ways to do it:

方法はいくつかあります。

Extend Mode

You’ll get extend-mode by returning an object.

object を返すことで、extended-mode になります。

Let’s say you want to add SASS support to Storybook. This is how to do it. Add the following content to a file called webpack.config.js in your Storybook config directory (.storybook by default ).

SASS のサポートを storybook に導入したい場合には、次のようにしてください。webpack.config.js という名前のファイルを config ディレクトリに配置して (初期設定では .storybook です。) 次のコンテンツを追加しましょう。

const path = require("path");

module.exports = {
  module: {
    rules: [
      {
        test: /\.scss$/,
        loaders: ["style-loader", "css-loader", "sass-loader"],
        include: path.resolve(__dirname, "../")
      }
    ]
  }
};

Since this config file stays in the Storybook directory, you need to set the include path as above. If the config directory stays in a different directory, you need to set the include path relative to that.

この設定ファイルは storybook のディレクトにあるので、include パスを上記のようにする必要があります。もしコンフィグ用のディレクトリーがこれとは異なる場所にある場合には、そのパスに対して相対的に正しいものになるように変更してください。

You also need to install the loaders (style, css, sass, as well as node-sass) used in above config manually.

また上記の設定で使用している loader たちもインストールする必要があります。

Once you create this webpack.config.js file, Storybook won’t load the default Webpack config other than loading JS files with the Babel loader. This will disable included functionality like svg loading. Read on to learn how to retain defaults.

このカスタマイズした webpack.config.js を用いる場合には、Storybook はデフォルトの webapck 設定ファイルはロードしないように変更されます。(? Babel ローダーによってロードされる JS ファイル以外は ?) これによって svg ローディング等の default 設定に含まれていた機能は、使えなくなります。default の昨日も保持したままカスタマイズする方法については、続くこの記事を参照してください。

Supported Webpack Options

You can add any kind of Webpack configuration options with the above config, whether they are plugins, loaders, or aliases. But you won’t be able to change the following config options:

webpack のどんな種類の設定も上記ファイルに含めることができます。例えば plugin や alias や loaders といったものです。ただし、以下の設定はすることができません。

  • entry
  • output
  • js loader with babel

For the advanced usage we strongly recommend full control mode.

より高度な用法の場合には、full control mode を使用することを推奨します。

Full Control Mode

Sometimes, you will want to have full control over the webpack configuration. Maybe you want to add different configurations for dev and production environments. That’s where you can use our full control mode.

webpack の設定を完全にコントロールしたい場合があるとおもいます。よくあるケースとしては、開発環境と本番環境で異なる設定をした場合です。そういう場合には full control mode を使用してください。

To enable that, you need to export a function from the above webpack.config.js file, just like this:

その場合には、webpack.config.js file が fuction を export するようにしてください。

const path = require("path");

// Export a function. Accept the base config as the only param.

// 関数を export する。これによって base となる設定を param として受け取ります。
module.exports = (storybookBaseConfig, configType) => {
  // configType has a value of 'DEVELOPMENT' or 'PRODUCTION'
  // You can change the configuration based on that.
  // 'PRODUCTION' is used when building the static version of storybook.

  // configType は 'DEVELOPMENT' or 'PRODUCTION' を受け取ります。
  // その値に基づいて設定を変更することができます。
  // 'PRODUCTION' は storybook の static バージョンをビルドした際に使われます。

  // Make whatever fine-grained changes you need

  // ここで望む設定をしましょう
  storybookBaseConfig.module.rules.push({
    test: /\.scss$/,
    loaders: ["style-loader", "css-loader", "sass-loader"],
    include: path.resolve(__dirname, "../")
  });

  // Return the altered config

 // 変更された設定を返します
  return storybookBaseConfig;
};

Storybook uses the config returned from the above function. So, try to edit the storybookBaseConfig with care. Make sure to preserve the following config options:

Storybook は上記の関数が返す設定を使用します。ですので、storybookBaseConfig の変更は注意深く行ってください。次の設定項目は変更しないでください。

  • entry
  • output
  • first loader in the module.loaders (Babel loader for JS)
  • all existing plugins

If your custom webpack config uses a loader that does not explicitly include specific file extensions via the test property, it is necessary to exclude the .ejs file extension from that loader.

ご自身で設定した webpack 設定ファイルが、loader を使っていて、しかもそれが明示的に特定のファイル拡張子を test プロパティ経由で指定してない場合には、.ejs file extension をその loader から除外する必要があります。

Full control mode + default

You may want to keep Storybook’s default config, but just need to extend it. If so, this is how you do it using the Full Control Mode. Add following content to the webpack.config.js in your Storybook config directory.

Storybook の default 設定はそのままにしておきたいが、しかし拡張する必要があるときがありますね。その場合にお full control mode を使うことができます。以下のコンテンツを webpack.config.js に追加してください。

const path = require("path");

module.exports = (baseConfig, env, defaultConfig) => {
  // Extend defaultConfig as you need.

  // ここで必要な拡張を行ってください

  // For example, add typescript loader:

  // 例えば typescript loader を追加するには以下のようにします
  defaultConfig.module.rules.push({
    test: /\.(ts|tsx)$/,
    include: path.resolve(__dirname, "../src"),
    loader: require.resolve("ts-loader")
  });
  defaultConfig.resolve.extensions.push(".ts", ".tsx");

  return defaultConfig;
};

For full instructions on Typescript setup, check our dedicated Typescript page.

Typescript に関する設定についてより情報が必要な場合はこのページを参照してください。

Using Your Existing Config

You may have an existing Webpack config for your project. So, you may need to copy and paste some config items into Storybook’s custom Webpack config file.

既にプロジェクト用の webpack 設定ファイルがある場合には、それをコピペして使おうと思うと思います。

But you don’t need to. There are a few options:

しかしそんなことはする必要はないです。そのための方法がいくつかあります。

  • Import your main Webpack config into Storybook’s webpack.config.js and use the loaders and plugins used in that.
  • Create a new file with common Webpack options and use it in both inside the main Webpack config and inside Storybook’s webpack.config.js.
  • メインの webpack 設定ファイルを storybook の webpack.config.js に import して、その中でツクァレている loders と plugins を使用する。
  • 新しいファイルを作って、共通する項目をそこに与えて、それを main の webpack 設定ファイルでも、storybook の webpack.config.js の中でも使う。
31
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
26