humaans / next-img

A Next.js plugin for embedding optimized images.

Home Page:https://humaans.github.io/next-img/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Possible to have dynamic requires?

dalanmiller opened this issue · comments

commented

Is it possible to have dynamic require paths?

import * as React from 'react'
import {Picture} from 'next-img'

type Props = {
    src: string
}

const Image = ({ src } : Props) =>  {
  return (
    <Picture className="object-cover" src={require(`../public/images/products/${src}`)} />
  );
}

export default Image

This breaks for me when src is equal to `6607330/1.jpg' and an example path structure I have is:

public/images/products/6411401/1.jpg

Screen Shot 2020-08-06 at 10 46 01 pm

commented

Human error, actual jpg files had extension .JPG

Having this same issue but specifically when the require includes a ?.
Eg. This first one would fail, where the second one would succeed.

  const stuff = "tree.jpg";
  const stuff2 = "?sizes=375";

   return (<Picture
        src={[
          require(`../assets/images/${stuff}${stuff2}`),
          require(`../assets/images/${stuff}`),
        ]}
        breakpoints={[768]}
      />)

Question: How should we handle importing in a directory of images?