なぽろぐ

気ままに感じたことを記事にまとめます。

Next.js で Babylon.js を扱う

Next.js と Babylon.js とwebGL が全く分からない俺

分からないので動かしたかった.バンドラーとして Next.js つかったら next.config.js 書かなきゃ動かなかったので備忘録的に文字に起こしておきます.

Babylon.js を動かす

babylonjs で npm ライブラリも公開されているが nextjs だと動かないので @babylonjs/core を使用する

yarn add -D next-transpile-modules next-compose-plugins
yarn add @babylonjs/core
const withTM = require('next-transpile-modules')(['@babylonjs/core']);
const withPlugins = require('next-compose-plugins');

const nextConfig = {
  /* 任意の config */ 
}
module.exports = withPlugins([
  [withTM],
], nextConfig);

これだけで build ができるようになります. next-transpile-module が必要なのは @babylonjs/core の js ファイルが es6 import を使用してるからです.@babylonjs/core を install したあとに node_modules をみてみるとわかると思います.

shader ファイルを raw-loader で読む

.glsl, .vert, .frag ファイルを raw-loader で string として読み込んで使えるようにします. next.config.js は babylonjs を使えるようにしたものを拡張しています.

yarn add -D raw-loader glslify-loader
const withTM = require('next-transpile-modules')(['@babylonjs/core']);
const withPlugins = require('next-compose-plugins');

const nextConfig = {
  webpack: (config, options) => {
    config.module.rules.push({
      test: /\.(glsl|frag|vert)$/,
      use: [
        options.defaultLoaders.babel,
        {
          loader: "raw-loader"
        },
        {
          loader: "glslify-loader"
        },
      ],
      exclude: /node_modules/,
    });
    return config;
  }
}

module.exports = withPlugins([
  [withTM],
], nextConfig);

import fragment from "./fragment.frag" としたときに fragment が string になるように typescript の型定義も追加しておきます.

declare module "*.vert" {
  declare const value: string;
  export default value;
}

declare module "*.frag" {
  declare const value: string;
  export default value;
}

declare module "*.glsl" {
  declare const value: string;
  export default value;
}

以上です.もしこれで動いたならばうれしいです.