programing

웹 팩을 사용하여 디렉토리에서 동적으로 이미지 가져오기

lovecodes 2023. 3. 26. 12:13
반응형

웹 팩을 사용하여 디렉토리에서 동적으로 이미지 가져오기

ES6를 통해 웹 팩에 이미지와 아이콘을 Import하기 위한 현재 워크플로우는 다음과 같습니다.

import cat from './images/cat1.jpg'
import cat2 from './images/cat2.svg'
import doggy from './images/doggy.png'
import turtle from './images/turtle.png'

<img src={doggy} />

이건 금방 지저분해지잖아내가 원하는 것은 이렇다.

import * from './images'

<img src={doggy} />
<img src={turtle} />

특정 디렉토리에서 모든 파일을 이름 sans 확장자로 동적으로 Import하고 필요에 따라 사용할 수 있는 방법이 있을 것 같습니다.

이 일을 본 사람, 아니면 이 일에 대해 가장 좋은 방법을 생각해 본 사람?


갱신:

선택한 답변을 사용하여 다음을 수행할 수 있습니다.

function importAll(r) {
  let images = {};
  r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
  return images;
}

const images = importAll(require.context('./images', false, /\.(png|jpe?g|svg)$/));

<img src={images['doggy.png']} />

특정 디렉토리에서 모든 파일을 이름 sans 확장자로 동적으로 Import하고 필요에 따라 사용할 수 있는 방법이 있을 것 같습니다.

ES6에는 없습니다.의 요점은import그리고.export즉, 코드를 실행하지 않고 정적으로 의존성을 결정할 수 있습니다.

다만, Web 팩을 사용하고 있기 때문에, 을 참조해 주세요.다음 기능을 사용할 수 있습니다.

function importAll(r) {
  return r.keys().map(r);
}

const images = importAll(require.context('./', false, /\.(png|jpe?g|svg)$/));

쉬워요.사용할 수 있습니다.require(스태틱 방식, Import는 다이내믹 파일 전용) 내부,render. 다음 예시와 같습니다.

render() {
    const {
      someProp,
    } = this.props

    const graphImage = require('./graph-' + anyVariable + '.png')
    const tableImage = require('./table-' + anyVariable2 + '.png')

    return (
    <img src={graphImage}/>
    )
}

이 문제를 해결하기 위한 기능적 접근법:

const importAll = require =>
  require.keys().reduce((acc, next) => {
    acc[next.replace("./", "")] = require(next);
    return acc;
  }, {});

const images = importAll(
  require.context("./image", false, /\.(png|jpe?g|svg)$/)
);

au.png, nl.png 등의 이름의 png 국가 플래그 디렉토리가 있습니다.다음과 같은 일이 있습니다.

-svg-country-flags
 --png100px
   ---au.png
   ---au.png
 --index.js
 --CountryFlagByCode.js

index.displaces를 표시합니다.

const context = require.context('./png100px', true, /.png$/);

const obj = {};
context.keys().forEach((key) => {
  const countryCode = key.split('./').pop() // remove the first 2 characters
    .substring(0, key.length - 6); // remove the file extension
  obj[countryCode] = context(key);
});

export default obj;

난 이런 파일을 읽었어

CountryFlagByCode.js

import React from 'react';
import countryFlags from './index';

const CountryFlagByCode = (countryCode) => {
    return (
        <div>
          <img src={countryFlags[countryCode.toLowerCase()]} alt="country_flag" />
        </div>
      );
    };

export default CountryFlagByCode;

업데이트 질문을 잘 이해하지 못한 것 같습니다.@펠릭스는 맞혔으니 그의 답을 확인해봐.다음 코드는 Nodejs 환경에서만 작동합니다.

를 추가합니다.index.js줄서다images폴더

const testFolder = './';
const fs = require('fs');
const path = require('path')

const allowedExts = [
  '.png' // add any extensions you need
]

const modules = {};

const files = fs.readdirSync(testFolder);

if (files && files.length) {
  files
    .filter(file => allowedExts.indexOf(path.extname(file)) > -1)
    .forEach(file => exports[path.basename(file, path.extname(file))] = require(`./${file}`));
}

module.exports = modules;

이렇게 하면 다른 파일에서 모든 파일을 Import할 수 있으며 Wepback은 해당 파일을 해석하여 필요한 파일을 로드합니다.

여기 제가 Reactjs에서 만든 기능 컴포넌트가 있습니다. 이 컴포넌트는 모든 이미지를 간단하게 표시하기 위해media폴더(컴포넌트와 동일한 수준)를 사용하여 웹 팩 문서와 여기에 있는 몇 가지 답변을 사용합니다.

import React from 'react';

const cache = {};

function importAll(r) {
    r.keys().forEach((key) => (cache[key] = r(key)));
}
// Note from the docs -> Warning: The arguments passed to require.context must be literals!
importAll(require.context("./media", false, /\.(png|jpe?g|svg)$/));

const images = Object.entries(cache).map(module => module[1].default);


const MediaPage = () => {
    return (
        <>
            <p>Media Page..</p>

            {images.map(image => (
                <img style={{width: 100}} src={image} />
            ))}
        </>
    );
}

export default MediaPage;

미디어 디렉토리에서 렌더링된 이미지

이미지를 로드한 방법으로 파일 이름은 매핑할 때 손실됩니다.cache오브젝트입니다만, 필요한 경우는,cache키가 파일 이름이기 때문에 직접 객체를 만듭니다.

// example with styles just for clarity
return (
    <>
        <p>Media Page..</p>

        {Object.entries(cache).map(module => {
            const image = module[1].default;
            const name = module[0].replace("./","");
            return (
                <div style={{float: 'left', padding: 10, margin: 10, border: '2px solid white' }}>
                    <img style={{width: 100, margin: 'auto', display: 'block'}} src={image} />
                    <p>{name}</p>
                </div>
            )
        })}
    </>
);

파일 이름이 있는 이미지

언급URL : https://stackoverflow.com/questions/42118296/dynamically-import-images-from-a-directory-using-webpack

반응형