Next.jsでthree.jsのexamplesを利用する

three.jsのリポジトリにはsrcディレクトリと同階層にexamplesディレクトリがあり、有用なツールが多数用意されている。Next.jsからこれらを利用するには、next.config.jsにちょっとした設定が必要。

resolve.modulesでも同じことができるが、aliasの方が意味的によさそう。

// next.config.js
const path = require('path')

module.exports = {
  webpack: (config) => {
    config.resolve.alias['ThreejsExample'] = path.resolve(__dirname, 'node_modules/three/examples')
    return config
  },
}
// FooComponent.js
import { GLTFLoader } from 'ThreejsExample/jsm/loaders/GLTFLoader'

最初ローカルに全然examplesが落ちてこなくて困ったんだけど、yarnのautocleanが有効になってたせいだった。