cyrilwanner / next-optimized-images

🌅 next-optimized-images automatically optimizes images used in next.js projects (jpeg, png, svg, webp and gif).
MIT License
2.21k stars 93 forks source link

[Canary] Can't import component when using `require()` in a prop #188

Open ryanrouleau opened 4 years ago

ryanrouleau commented 4 years ago

So this is pretty strange.

I have a component that looks like:

components/common/FallbackImg.tsx

import React, { ImgHTMLAttributes } from 'react';

interface Props extends ImgHTMLAttributes<HTMLImageElement> {
  src: string;
  srcWebp: string;
  alt: string;
};

const FallbackImg: React.FC<Props> = ({ src, srcWebp, alt, ...props}) => (
  <picture>
    <source srcSet={srcWebp} type="image/webp" />
    <source srcSet={src} />
    {/* eslint-disable-next-line react/jsx-props-no-spreading */}
    <img alt={alt} loading="lazy" src={src} {...props} />
  </picture>
);

export default FallbackImg;

then I use it like:

pages/index.tsx

import FallbackImg from '../components/common';

// imagine function component stuff goes here
<FallbackImg
  src={require('pathtoimg')}
  srcWebp={require('pathtoimg?webp'}
  alt="some image"
/>

I get the error

./pages/index.tsx
Error: <omitted for privacy>/pages/index.tsx: Cannot find module '../components/common' from '<omitted for privacy>/pages'

However if I remove the require in the usage of FallbackImg and just pass undefined for example, it works fine (albeit the image is broken of course on the page since it's undefined).

It also works fine if I define FallbackImg directly in pages/index.tsx (with the require) and don't import it from somewhere else.

Any idea why this would happen? Unfortunately <Img /> doesn't fit our exact use case so we need something like the above.

Thanks! And great work with this package it's fantastic 🥇

Edit: tested on a clean create-next-app and the same behavior occurs

ryanrouleau commented 4 years ago

Switching the prop name from src to something else like srcJpeg makes it work 🙏 . Must be some conflict w/ the prop being named src. I'm gonna leave this as open so you can take a look at it incase it's a symptom of something else, but feel free to close it if it's expected behavior.

cyrilwanner commented 4 years ago

Hi @ryanrouleau Thank you very much for the bug report. That is definitely not an expected behavior and may come from a bug in the babel plugin. I'll look into it.