5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

StorybookをNuxt.jsのアセットに対応させる

Last updated at Posted at 2018-11-16

Nuxt.jsでアセットを取り扱うのって、めっちゃ楽ですよね。
アセット - Nuxt.js
この書き方に慣れちゃって、CSS内で

background: url('~/assets/images/{イメージ名}.jpg');

とかよく使ってるんですけど、これだとStorybookではhttp://localhost:6006/assets/images/{画像名}.jpgになっちゃって、うまい事引っ張ってくれないんです。

ということで、NuxtのWebpackの中身を見ながら、対策練ってみました。

環境

Nuxt v1.3.0
Storybook vue v3.4.11

結論

/.storybook/webpack.conf.jsで css-loader の option に alias を追加すれば読み込めます。

/.storybook/webpack.conf.js
const path = require('path')
const rootPath = path.resolve(__dirname, '../')

module.exports = (baseConfig, env, defaultConfig) => {

  defaultConfig.resolve.alias['@'] = rootPath
  defaultConfig.resolve.alias['~'] = rootPath
  defaultConfig.resolve.alias['vue$'] = 'vue/dist/vue.esm.js'

  const vueLoader = defaultConfig.module.rules.find(({test}) => {
    return test.toString() === '/\\.vue$/'
  })

  vueLoader.options = {
    loaders: {
      css: [
        'vue-style-loader',
        {
          // この部分
          loader: 'css-loader',
          options: {
            importLoaders: 0,
            alias: {
              '/assets': rootPath + '/assets'
            }
          }
        }
      ]
    }
  }

  const cssLoader = defaultConfig.module.rules.find(({test}) => {
    return test.toString() === '/\\.css$/'
  })
  cssLoader.use = [
    { loader: 'vue-style-loader' },
    {
      // この部分
      loader: 'css-loader',
      options: {
        importLoaders: 0,
        alias: {
          '/assets': rootPath + '/assets'
        }
      }
    }
  ]

  return defaultConfig
}

Nuxt 2系から~/assets~assetsになったらしいので、alias 部分を

alias: {
  'assets': rootPath + '/assets'
}

に変えてあげると良さそう(試してない)。

5
8
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
5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?