3
0

More than 3 years have passed since last update.

Next + Storybook で「 importSource cannot be set when runtime is classic」

Last updated at Posted at 2021-06-15

Gatsbyに関しての記述はまぁまぁ見つかったのですがNextを使う時の記事が見つからなかったのでメモ

環境

  • Nextjs(10.0.6)
  • storybook(6.2.9)
  • theme-ui(0.9.1)

状況

Sample.tsx
/** @jsxImportSource theme-ui */

type Props = ComponentProps<'div'> & {};

export default function Sample(props: Props): JSX.Element {
  return <div sx={{ backgroundColor: '#ddd'}}} {...props} />
}

こんな感じのコンポーネントをStorybookで表示しようとするとエラーが出ました

$ yarn storybook
...省略
ERROR in ./lib/components/sample/Sample.tsx
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /Users/username/project/path/sample/Sample.tsx: importSource cannot be set when runtime is classic.

原因

「when runtime is classic」と書いてあるので@babel/preset-reactの設定を変えてruntimeをclassicじゃない何かに変えてあげればいいことはわかるのですが...

storybookのmain.jsをいろいろいじって@babel/preset-reactの設定を変えても治りませんでした

結果気づいたのが、実はエラーの出たプロジェクトではルートディレクトリに.babelrc.jsonを作っていたんですよね

↓実際の.babelrc.json

babelrc.json
{
  "presets": ["next/babel"],
  "plugins": [
    [
      "prismjs",
      {
        "languages": [
          "javascript",
        ],
        "plugins": ["line-numbers", "diff-highlight"],
        "css": true
      }
    ]
  ]
}

この設定のnext/babelの中で@babel/preset-reactが使われてるのがエラーの原因でした

解決策

結果としてnext/babelを設定して@babel/preset-reactの設定を変えてあげればエラーが出なくなりました

babelrc.json
{
  "presets": [["next/babel", {"preset-react": {"runtime": "automatic"}}]]
}

まとめ

公式の説明を読むと「next/babelが内包するpresetsについてはこのファイル読んでね!」みたいな記述があるのですが、「英語だ!コードだけ追えばいいや!」と考え完全に見落としてました(何回やるんだ...)

とはいえ、この設定なしでもNextがビルドできているのは何故だろう...

ついでに

実はコンポーネントを作るたびに毎回/** @jsxImportSource theme-ui */と書いていたので、書かなくていいように設定加えました

babelrc.json
{
  "presets": [["next/babel", {"preset-react": {"runtime": "automatic", "importSource":"theme-ui"}}]],
}
3
0
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
3
0