みかづきブログ・カスタム

基本的にはちょちょいのほいです。

動的インポートをつかってNext.jsでサーバサイドレンダリングしないコンポーネントをつくる 💻

Next.js + PixiJSでサイトをつくっていたとき、PixiJSをつかったコンポーネントを読み込もうとすると、

Server Error
ReferenceError: self is not defined

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source
external%20%22pixi.js%22 (1:0) @ eval

> 1 | module.exports = require("pixi.js");

と、エラーがでました。

解決策は簡単で、PixiJSを使っているコンポーネントをSSRの対象から外せばOKです。

import PixiTemplate from './PixiTemplate';

export default function IndexPage() {
  return (
    <div>
      <PixiTemplate />
    </div>
  );
}

的な感じで読み込んでいたテンプレートを、

import dynamic from 'next/dynamic';

const PixiTemplateNoSSR = dynamic(() => import('./PixiTemplate'), {
  ssr: false
});

export default function IndexPage() {
  return (
    <div>
      <PixiTemplateNoSSR />
    </div>
  );
}

という感じに変更してあげればOKです。

nextjs.org

追記

名前付きエクスポートを使っているコンポーネントの場合は こちら

blog.kimizuka.org