Read contents of file into array inside vue component

Asked By: Anonymous

directory structure

Inside my media.txt file, I have:


I have the following Vue carousel component:


        <v-carousel-item v-for="(item,i) in items" :key="i" :src="item.src"></v-carousel-item>


var cache = {};
// const images = require.context('../static/', false, /.png$|.jpg/);
// const images = require.context('../static/', false, /.png$|.jpg|.mp4/); // WORKING
const images = require.context('../static/media.txt', false, /.png$|.jpg|.mp4/);
var imagesArray = Array.from(images.keys());
// const images = ["./52lv.PNG", "./Capture1.PNG", "./maps.PNG"]
var constructed = [];
function constructItems(fileNames, constructed) {
  fileNames.forEach(fileName => {
      'src': fileName.substr(1)
  return constructed;
console.log('items ');
// At build-time cache will be populated with all required modules. 
var res = constructItems(imagesArray, constructed);
export default {
  data: function() {
    return {
      items: res

I want to read the images from the media.txt file into an array, then populate the carousel src with these. I’ve been trying with Webpack’s require.context function, but I’m getting a module not found error.

How can I get this working?


Answered By: Anonymous

It looks like you’re trying to import a string array (JSON) into a variable. That string array should be delimited by square brackets like this:


require.context(dirPath, useSubDirs, filenameRegex) is not the appropriate API to use here, as that method imports multiple files from a specified directory. For instance, the code below tells Webpack to load *.png, *.jpg, and *.mp4 files from the directory named ../static/media.txt (which presumably is actually a file).

require.context('../static/media.txt', false, /.png$|.jpg|.mp4/) // DON'T DO THIS

Instead, you could simply use require('path/to/file.json') to import the specified file as a JSON object/array. For example, to import src/assets/media.json (containing the array mentioned at the top), the syntax would be:

// e.g., in src/components/Foo.vue
const media = require('../assets/media.json')
console.log(media) // => [ "foo", "bar" ]


techinplanet staff

techinplanet staff

Windows 10 Kaufen Windows 10 Pro Office 2019 Kaufen Office 365 Lizenz Windows 10 Home Lizenz Office 2019 Home Business Kaufen windows office 365 satın al follower kaufen instagram follower kaufen porno