Using npm dependencies in Phoenix apps

almirsarajcic

almirsarajcic

11 months ago

Adding npm dependencies to Phoenix apps is easy.
Run the npm install command, then update your app.js, mix.exs, and Dockerfile.

npm i --save clipboard --prefix assets

// app.js
import ClipboardJS from 'clipboard'

# mix.exs
"assets.setup": [
  "tailwind.install --if-missing",
  "esbuild.install --if-missing",
  "cmd --cd assets npm install"
],

# Dockerfile
RUN apt-get update -y \
    && apt-get install -y build-essential git npm \
    && apt-get clean && rm -f /var/lib/apt/lists/*_*

...

COPY assets/package.json assets/package-lock.json ./assets/

RUN npm --prefix ./assets ci \
    --progress=false \
    --no-audit \
    --loglevel=error

COPY assets assets

RUN mix assets.deploy

RUN mix compile