programing

vue.js/nuxt.js를 사용하여 디렉토리 내의 모든 이미지 파일을 가져오는 방법

bestcode 2022. 8. 31. 22:45
반응형

vue.js/nuxt.js를 사용하여 디렉토리 내의 모든 이미지 파일을 가져오는 방법

nuxt.js 프로젝트를 진행 중 오류가 발생하였습니다.

브라우저에서 다음 오류가 나타납니다.

__webpack_require__(...).context is not a function

터미널에서 다음 오류가 발생합니다.

Critical dependency: require function is used in a way in which dependencies cannot be statically extracted 

여기 제 코드가 있습니다.

<script>
export default {
  name: 'SectionOurClients',
  data() {
    return {
      imageDir: '../assets/images/clients/',
      images: {},
    };
  },

  mounted() {
    this.importAll(require.context(this.imageDir, true, /\.png$/));
  },

  methods: {
    importAll(r) {
      console.log(r)
    },
  },
};
</script>

저는 여기서 의 스크립트를 사용했습니다.

제발 도와주세요, 고마워요.


편집: @MaxSinev의 답변을 따라가면 작업 코드는 다음과 같습니다.

<template lang="pug">
  .row
    .col(v-for="client in images")
      img(:src="client.pathLong")
</template>

<script>
export default {
  name: 'SectionOurClients',
  data() {
    return {
      images: [],
    };
  },

  mounted() {
    this.importAll(require.context('../assets/images/clients/', true, /\.png$/));
  },

  methods: {
    importAll(r) {
      r.keys().forEach(key => (this.images.push({ pathLong: r(key), pathShort: key })));
    },
  },
};
</script>

웹 팩 문서:

인수가 전달되었습니다.require.context리터럴임에 틀림없어!

그래서 내 생각엔 당신 사건에서require.context실패했습니다.

대신 리터럴 전달을 시도합니다.imageDir변수

mounted() {
    this.importAll(require.context('../assets/images/clients/', true, /\.png$/));
},

이는 웹 팩이 번들 중에 런타임 변수 값을 해결할 수 없기 때문에 필요합니다.

언급URL : https://stackoverflow.com/questions/54095215/how-to-get-all-the-image-files-in-a-directory-using-vue-js-nuxt-js

반응형