DEV Community

nishinoshake
nishinoshake

Posted on

Storybook for EJS

This is a minimal example to use Storybook with EJS.

Directory structure

├ .storybook
│  ├ config.js
│  └ webpack.config.js
└ src
   ├ components
   │  └ button.ejs
   └ stories
      └ button.stories.js

Install package

npm install --save-dev @storybook/html babel-loader @babel/core ejs-compiled-loader

Edit package.json

{
  "scripts": {
    "storybook": "start-storybook"
  }
}

Configure Storybook

// .storybook/config.js

import { configure } from '@storybook/html'

function loadStories() {
  const req = require.context('../src/stories', true, /\.stories\.js$/)
  req.keys().forEach(filename => req(filename))
}

configure(loadStories, module)

Add EJS loader to webpack config

// .storybook/webpack.config.js

const path = require('path')

module.exports = async ({ config }) => {
  config.module.rules.push({
    test: /\.ejs$/,
    loaders: ['ejs-compiled-loader'],
    include: path.resolve(__dirname, '../src/components')
  })

  return config
}

Create component

<!-- src/components/button.ejs -->
<button><%=label%></button>

Create story

// src/stories/button.stories.js

import { storiesOf } from '@storybook/html'
import buttonTemplate from '../components/button.ejs'

storiesOf('Button', module)
  .add('with text', () => buttonTemplate({ label: 'Button!' }))

Run

Alt Text

npm run storybook

final code on GitHub.
https://github.com/nishinoshake/storybook-ejs-example

Resources

Top comments (0)