Phoenix Three

A Mix task package for easily integrating Three.js into Phoenix projects. Automatically downloads Three.js files from CDN and configures your app.js imports.

Features

Installation

Add phoenix_three to your list of dependencies in mix.exs:

def deps do
  [
    {:phoenix_three, github: "benjaminjacobberg/phoenix_three", only: :dev, runtime: false}}
  ]
end

Then run:

mix deps.get

Usage

Quick Start

Set up Three.js in your Phoenix project with one command:

mix threejs.setup

This will:

  1. Download Three.js files to assets/vendor/three/
  2. Add the import to your assets/js/app.js
  3. Make THREE available globally for hooks

Individual Commands

Download Three.js files only:

mix threejs.download

Configure app.js imports only:

mix threejs.configure

Options

Version Selection:

# Download specific Three.js version
mix threejs.setup --version 0.176.0

Force Overwrite:

# Overwrite existing files and imports
mix threejs.setup --force

What Gets Added to Your Project

Files Downloaded

App.js Modifications

The task adds this import to your assets/js/app.js:

import * as THREE from "../vendor/three/three.module.js";

And this global assignment after your window.liveSocket = liveSocket line:

// Make THREE.js available globally for hooks
window.THREE = THREE

Using Three.js in LiveView Hooks

After setup, you can use Three.js in your Phoenix LiveView hooks:

// assets/js/app.js
let Hooks = {}

Hooks.ThreeScene = {
  mounted() {
    // THREE is available globally
    const scene = new THREE.Scene()
    const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
    const renderer = new THREE.WebGLRenderer()

    renderer.setSize(this.el.clientWidth, this.el.clientHeight)
    this.el.appendChild(renderer.domElement)

    // Your Three.js code here...
  }
}

let liveSocket = new LiveSocket("/live", Socket, {hooks: Hooks, params: {_csrf_token: csrfToken}})

In your LiveView template:

<div id="three-container" phx-hook="ThreeScene"></div>

Integration with Build Process

Add to your mix.exs aliases for automatic setup:

defp aliases do
  [
    setup: ["deps.get", "threejs.setup", "assets.setup", "assets.build"],
    "assets.deploy": ["threejs.setup", "assets.deploy"]
  ]
end

Available Three.js Versions

The package downloads from CDNJS. You can use any version available there:

Troubleshooting

"assets/js/app.js not found" error:

Import conflicts:

Version not found:

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/benjaminjacobberg/phoenix_three.

License

The package is available as open source under the terms of the MIT License.

Credits