【问题标题】:Vue.js webpack : how to get the list of files in a directory?Vue.js webpack:如何获取目录中的文件列表?
【发布时间】:2018-07-28 17:49:58
【问题描述】:

我正在尝试获取 SPA 静态应用程序的“资产/插图”目录中所有文件的列表作为 JSON 对象,以便在我的 Vuex 商店中重复使用

资产/插图目录结构是:

assets
  illustrations
    ill-1
       prop-1-1.jpg
       prop-1_2.jpg
    ill-2
       prop-2-1.jpg
       prop-2_2.jpg
    ill-3
       prop-3-1.jpg
       prop-3_2.jpg

我的目标是得到这样的对象:

  { illustrations: [ill-1: [prop-1-1.jpg, prop-1_2.jpg], ill-2: [prop-2-1.jpg, prop-2_2.jpg], ill-3: [prop-3-1.jpg, prop-3_2.jpg]] }

在我的 App.vue 中,当应用组件被挂载时,我触发了一个方法 getIllustrations()

<script>
export default {
  name: 'app',
  data () {
    return {}
  },
  methods: {
    getIllustrations () {
      const path = require('path')
      const fs = require('fs')
      fs.readdir(path.join(__dirname, 'assets/illustrations'), (err, items) => {
        if (err) { console.log(err) }
        console.log(items)
      })
    }
  },
  mounted () {
    this.getIllustrations()
  }
}
</script>

但我得到一个错误:

 Error in mounted hook: "TypeError: fs.readdir is not a function"

我也尝试在 main.js 文件中运行这个函数(它在服务器上运行..)同样的错误..

我哪里错了?感谢反馈

【问题讨论】:

  • 运行时需要动态读取目录还是静态构建?

标签: webpack vue.js fs


【解决方案1】:

您可以利用 webpack 的 require.context() 在编译时列出给定目录中的文件。

https://webpack.js.org/guides/dependency-management/

const illustrations = require.context(
  '@/assets/illustrations',
  true,
  /^.*\.jpg$/
)
console.log(illustrations.keys())

【讨论】:

  • 请注意,对于自定义文件格式(如 yaml),您需要一个自定义加载器才能在没有警告的情况下工作,我认为使用某些加载器 + 正则表达式它会增加您的包大小/内存消耗在文档中说明。
【解决方案2】:

fs 是服务器端模块。你不能在浏览器中使用fs,这个没有解决办法,技术上是不可能的。

https://github.com/vuejs-templates/webpack/issues/262

【讨论】:

  • 不对,可以使用require.context()
猜你喜欢
  • 2020-09-11
  • 1970-01-01
  • 2018-09-19
  • 1970-01-01
  • 2012-09-22
  • 2019-11-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多