In javascript, is it possible to shorthand put all imports in an array for export?

Viewed 306

The current situation is like follows:

// ./img/index.js:

import some-image from "./some-image.png";
import some-other-image from "./some-other-image.png";
// About 50 of these imports

export const imageArray = [some-image, some-other-image] //...and the other 48 imported images go in this array

This turn out, when typed in full, to be quite the lengthy export statement. What I want to achieve is fill the export imageArray with all the imported image in a more automated way without having to copy paste the var names from import.

Something like:

export const imageArray = [this.Imports];

Is something like this possible?

2 Answers

You can do this using babel-plugin-wildcard.

import * as images from "./images/*.png"

export default images
// or
export const imageArray = images

If you want to do it without any third module:

const fs = require('fs');
const path = require('path');

// In this example i supose you have only images at the folder!
async function getImages(folder) {
  const images = [];

  const files = await fs.promises.readdir(folder, { withFileTypes: true });
  for (let file of files) {
    images.push(path.join(__dirname, folder, file));
  }

  return images;
}

const imageArray = [];

// The '.' should be the path where are your images at.
const array = getImages('.'); 

// It could be like this or doing the reverse call when importing this imageArray...
array.forEach(el => {
  import image from el;
  imageArray.push(image)
});

export imageArray; 
Related