wheatandcatの開発ブログ

React Nativeで開発しているペペロミア & memoirの技術系記事を投稿してます

Next.jsでSSRをサポートしていないComponentパッケージを導入する方法

Next.jsで作成してLPサイトにSSRをサポートしていないComponentパッケージを導入しようとしたところ、意外とハマったので記事にした。

PR

github.com

実装

お試しでmemoir用のKo-fiのページを作ってみたのでNext.jsで作成したLPサイトにリンクを追加する開発を行った。

ko-fi.com

リンクの追加は以下のパッケージを使用。

github.com

まず、ドキュメントの通りに以下のように実装したら、Global CSS cannot be imported from within node_modules.のエラーが発生した。

import KofiButton from "react-kofi-button";

(略)
     <KofiButton username="memoir22983" label="支援する" preset="thin" backgroundColor="#F680B2" />

調べたところ、以下の記事を発見。

zenn.dev

Next.jsでnode_module内でcssをimportしている場合は、以下のnext-remove-importsを使用して除外する必要がある。

github.com

以下の通りに追加。

next.config.js

/** @type {import('next').NextConfig} */
const path = require("path");
const removeImports = require("next-remove-imports")();

module.exports = removeImports({
    webpack(config) {
        config.resolve.alias["@components"] = path.join(__dirname, "components");
        config.resolve.alias["@hooks"] = path.join(__dirname, "hooks");
        config.resolve.alias["@lib"] = path.join(__dirname, "lib");
        return config;
    },
    reactStrictMode: true,
});

さらに、cssが除外されるので、pages/_app.tsxにimportを追加。

pages/_app.tsx

import "react-kofi-button/dist/KofiButton/style.scss";

これで起動して動くのかなと思ったが、今度はSyntaxError: Invalid or unexpected token; This error happened while generating the page. Any console logs will be displayed in the terminal window.のエラーが出力された。

こちらの件も調べたら、以下の記事が見つかった。

blog.kimizuka.org

SSRで使用できない処理を使用すると発生するエラーだったので、記事を参考に以下の用に修正。

components/organisms/Header/Header.tsx

import dynamic from "next/dynamic";

(略)

const KofiButton = dynamic(() => import("react-kofi-button/dist/KofiButton"), {
    ssr: false,
});


(略)
     <KofiButton username="memoir22983" label="支援する" preset="thin" backgroundColor="#F680B2" />

これで実行したらエラーもなくなり以下のように表示できるようになった。

スクリーンショット 2023-01-21 20 13 20

www.memoir-app.dev