LoginSignup
0
0

More than 1 year has passed since last update.

Gatsby.jsで「ModuleBuildError: Module build failed : SyntaxError: Only one default export allowed per module.」というエラーが出たときの対処法

Last updated at Posted at 2021-10-26

エラーメッセージ

ModuleBuildError: Module build failed (from ./node_modules/gatsby/dist/utils/babel-loader.js):
  SyntaxError: /Users/user_name/git/maiamea/portfolio/src/pages/hello.jsx: Only one default export allowed per module. (31:
  0)
    29 |
    30 | export default HelloPage
  > 31 | export default Example
       | ^

エラー発生時のコード

src/pages/hello.jsx
import React, { useState } from 'react';

const HelloPage = () => {
    return (
        <main>
            <h1>Hello, World!!!</h1>
            <p style={
                {color:"red"}
            }>こんにちは</p>
            <h2>はじめてのGatsby</h2>
        </main>
    )
}

function Example() {
    const [count, setCount] = useState(0);
    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count+1)}>
                Click me
            </button>
        </div>
    )
}

export default HelloPage
export default Example

原因

1つのファイル内にexport defaltを複数書いていた。

対処法

export defaultには起点となるコンポーネントを書き、一緒のページに表示させたい他のコンポーネントは、起点となるコンポーネント内に<ExampleComponent></ExampleComponent>のように埋め込む。

修正後

src/pages/hello.jsx
import React, { useState } from 'react';

const HelloPage = () => {
    return (
        <main>
            <h1>Hello, World!!!</h1>
            <p style={
                {color:"red"}
            }>こんにちは</p>
            <h2>はじめてのGatsby</h2>
            <ExampleComponent></ExampleComponent>
        </main>
    )
}

function ExampleComponent() {
    const [count, setCount] = useState(0);
    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count+1)}>
                Click me
            </button>
        </div>
    )
}

export default HelloPage

実行結果(ブラウザ)

スクリーンショット 2021-10-26 15.09.05.png

参考サイト

0
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
0
0