Storybook for Angularで~(チルダ)のpathを解決する

Storybook for Angularを使用していてsassのimportで~(チルダ)を使うとpathを解決できずにエラーが出たので解決法のメモ

検証した際のversion

  • Angular 7.2
  • Storybook 5.0.5

とりあえずng new
ng new storybook-for-angular

次にstorybookのセットアップをします。 今回はAutomatic setupを使います。
npx -p @storybook/cli sb init --type angular

検証用のコンポーネントとsassファイルを追加したsrc配下のディレクトリは以下になります。

  src/
  ├── app
  │   ├── app.component.css
  │   ├── app.component.html
  │   ├── app.component.spec.ts
  │   ├── app.component.ts
  │   ├── app.module.ts
  │   └── components
  │       └── helloworld
  │           ├── helloworld.component.html
  │           ├── helloworld.component.scss
  │           ├── helloworld.component.spec.ts
  │           └── helloworld.component.ts
  ├── assets
  ├── browserslist
  ├── environments
  │   ├── environment.prod.ts
  │   └── environment.ts
  ├── favicon.ico
  ├── index.html
  ├── karma.conf.js
  ├── main.ts
  ├── polyfills.ts
  ├── stories
  │   └── index.stories.ts
  ├── styles
  │   └── _font.scss
  ├── styles.css
  ├── test.ts
  ├── tsconfig.app.json
  ├── tsconfig.spec.json
  └── tslint.json

helloworld.component.scss内で_font.scssをインポートしようとすると以下のエラーが発生する。

@import "~styles/font"
^
      File to import not found or unreadable: ~styles/font

解決法

.storybook配下にwebpack.config.jsを作成して以下の内容を追加する。

const path = require('path');

module.exports = ({ config, mode }) => {
  config.resolve.alias['styles'] = path.resolve(__dirname, '../src/styles');

  return config;
};

まとめ

Storybook v4でも同じエラーが出ますが、解決法は同じです。
webpack.config.jsの書き方がv5から若干変わっているのでv4の書き方に合わせてください。

Storybookで快適なコンポーネント開発を!

サンプルリポジトリ