【发布时间】: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 文件中运行这个函数(它在服务器上运行..)同样的错误..
我哪里错了?感谢反馈
【问题讨论】:
-
运行时需要动态读取目录还是静态构建?