LoginSignup
8
4

More than 1 year has passed since last update.

storybook next/image エラー解決:next.config.jsにドメイン設定してもダメ

Last updated at Posted at 2021-07-23

前提

環境

package.json
"dependencies": {
    "next": "^11.0.1",
    "react": "17.0.2",
    "react-dom": "17.0.2"
  },
"devDependencies": {
  "@babel/core": "^7.14.8",
  "@storybook/addon-actions": "^6.3.5",
  "@storybook/addon-essentials": "^6.3.5",
  "@storybook/addon-links": "^6.3.5",
  "@storybook/addon-postcss": "^2.0.0",
  "@storybook/react": "^6.3.5",
  "@testing-library/react": "^12.0.0",
  "@types/jest": "^26.0.24",
  "@types/node": "^15.6.1",
  "@types/react": "^17.0.6",
  "@types/react-dom": "^17.0.5",
  "@typescript-eslint/eslint-plugin": "^4.28.4",
  "autoprefixer": "^10.3.1",
  "babel-jest": "^27.0.6",
  "babel-loader": "^8.2.2",
  "eslint": "^7.31.0",
  "eslint-config-next": "^11.0.1",
  "eslint-config-prettier": "^8.3.0",
  "husky": "^7.0.1",
  "identity-obj-proxy": "^3.0.0",
  "jest": "^27.0.6",
  "jest-watch-typeahead": "^0.6.4",
  "lint-staged": "^11.1.0",
  "postcss": "^8.3.6",
  "prettier": "^2.3.2",
  "tailwindcss": "^2.2.6",
  "typescript": "^4.2.4"
  }

エラー内容

Next.jsでコンポーネントを開発していると、Storybookで以下のエラーに遭遇しました。
storybook_next_image_error.png

next/image component, you passed a src value that uses a hostname in the URL that isn't defined in the images config in next.config.js.

これを見ると、どうやらnext/imageコンポーネントを活用するページで、next.config.jsのimagesで定義されていないURLをsrcに使用することはできないようです。

しかし、next.config.jsを作成し、上記のリンクのように設定してもエラーは解決しませんでした。

touch next.config.js

next.config.js

module.exports = {
  images: {
    domains: ['example.com'],
  },
};

解決した方法

.storybook/preview.jsに以下を追加

import * as nextImage from 'next/image';

Object.defineProperty(nextImage, 'default', {
  configurable: true,
  value: props => <img {...props} />
});


修正後 (.storybook/preview.js)
import '../src/styles/globals.css';
import * as nextImage from 'next/image';

Object.defineProperty(nextImage, 'default', {
  configurable: true,
  value: props => <img {...props} />
});

export const parameters = {
  actions: { argTypesRegex: '^on[A-Z].*' },
  controls: {
    matchers: {
      color: /(background|color)$/i,
      date: /Date$/,
    },
  },
};

参照

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