javaScript/nodeJs
require.context / 파일경로 가져오기.
부엉이사장
2023. 3. 8. 21:23
이미지파일을 디렉토리별로 분류해서 관리한다.
js파일에서 특정디렉토리에 어떤 파일들이 있는지 동적으로 알고싶은데
node처럼 path모듈을 사용할수도 없고..해서 찾아봤더니 require.context가 있더라
const context = require.context("../assets/img", false, /\.png$/);
for (const key of context.keys()) {
console.log(key);
}
참고로 assets/img폴더안에 있는 이미지들을 가져올거다.
require.context메서드 파라미터는 각각
첫번째 : 찾을 경로
두번째 : 불린값인데 하위 폴더까지 다가져올거냐 마냐임.
세번째 : 원하는 파일명 정규식
결과를 보면
./1.png
./2.png
./3.png
이렇게 나온다.