twopluszero / next-images

Import images in Next.js (supports jpg, jpeg, svg, png and gif images)
MIT License
948 stars 67 forks source link

Issues with image dynamic import #16

Closed advaitju closed 5 years ago

advaitju commented 5 years ago

I'm keeping images in an images/ folder and URLs in a data file. I'd like to dynamically import the images so I can load a large number of images easily.

I thought this could be done using dynamic imports, however it seems that functionality only supports Js modules. Will this be supported in the future or am I totally off the mark on this one?

import dynamic from 'next/dynamic';
import urls from '../urls';

const images = urls.map(url => dynamic(() => import(url));

I'm getting the error Error: Cannot find module.

arefaslani commented 5 years ago

Can you share an example URLs file?

advaitju commented 5 years ago

Example URLs files.

module.exports = [
  './images/image1.jpg',
  './images/image2.jpg',
  './images/image3.jpg',
];

For now I've decided to do this - which achieves what I wanted. Dynamic imports would be nice to have, but I guess they're not needed for this particular use case.

import image1 from './images/image1.jpg';
import image2 from  './images/image2.jpg';
import image3 from  './images/image3.jpg';

module.exports = [
  image1,
  image2,
  image3,
];

It would still be great to be able to import programatically if there are lots of images used in a grid/slider.

arefaslani commented 5 years ago

@advaitju I'll take a look ASAP.

AndrewIngram commented 5 years ago

I'd just use this babel plugin for this kind of thing:

https://github.com/novemberborn/babel-plugin-import-glob

advaitju commented 5 years ago

I'd just use this babel plugin for this kind of thing:

https://github.com/novemberborn/babel-plugin-import-glob

Thanks Andrew, I didn't know about this particular plugin. I think it might solve this use case.

arefaslani commented 5 years ago

@advaitju Do you think this plugin solves your issue? If so, we can close this issue.

advaitju commented 5 years ago

@advaitju Do you think this plugin solves your issue? If so, we can close this issue.

No worries, thanks for your help Aref. The plugin solves my problem.