Vue App workaround for dynamic directories with webpack require.context()

In my Vue app, I have set up a route that displays multiple image galleries. When a user clicks on a gallery, they are directed to a dynamic component that shows the images belonging to that specific gallery.

For instance, if the user sees two cards named foo and bar, clicking on them will lead them to /gallery/foo or /gallery/bar. The structure of my assets folder is as follows:

src/assets/images
├── foo
│   └── 1.jpg
└── bar
    └── 2.jpg

Each gallery has its own folder containing all the relevant images. This project is entirely static, with no access to databases or APIs, hence external resources are not applicable here.

I attempted to use Webpack's require.context(), but encountered issues when trying to use a dynamic path, as documented in Webpack Issue #4772.

The code snippet I experimented with:

data() {
  return {
    images: null
  }
),
mounted() {
    this.populatePage();
  }
},
methods: {
  populatePage() {
    const imagePath = `@/assets/images/${this.$route.params.id}/`;
    this.images = this.importAll(require.context(imagePath, true, /\.(jpe?g)$/));
  },
  importAll(r) {
     return r.keys().map(r);
  }
}

Due to using the variable imagePath in require.context(), the above approach did not work as expected. Simply using @/assets/images/ imports all JPG files in the directory, which is not desired.

What would be the most effective way to achieve the intended outcome here? It's crucial to avoid loading irrelevant images, considering the potentially large file sizes (~150kb each at high resolution) even after optimization.

I initially considered importing all images and extracting the folder name via regex from the webpack-generated chunk, but the directory gets omitted and replaced by a hash in the filename. Is there a method to append a directory to filenames in Vue or any other framework?

/img/1.2f159e72.jpg
/img/2.2c1da0da.jpg

Answer №1

Customizing Webpack is a breeze. By configuring it properly, you can maintain the directory structure of your project. Check out the file-loader documentation for more details.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        loader: 'file-loader',
        options: {
          name: '[path][name].[ext]',
        },
      },
    ],
  },
};

You can then effortlessly import an entire root directory (including subdirectories) and selectively choose which files from the gallery to use. Importing everything shouldn't worry you - remember, file-loader doesn't actually "load" the file online; it simply provides the URL of the file during the build process. To display the image in the browser, you'll need to use it within an img tag, for example.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason for my component rendering on the same page?

I have created a landing page with a button that is supposed to redirect to a Register component when clicked. However, instead of opening the Register component on a new page, it appears underneath my landing page. What could be causing this issue? App.j ...

Sending variables to another function in JavaScript

I am looking to transfer the variable "firstWord" along with its saved value from one method to another. var obj = { getWords: function () { var words = []; $('input').each(function () { words.push($(this).val( ...

Updating the current view in Rails with newly fetched data

NOTE: To make it easier, skip to the EDIT part below. Thank you! I am currently working on adding a simple feature to my app. The feature involves a view with a chart that depends on two query parameters: :from and :to. I am using "Chartkick" and below a ...

Utilize Paper.js to adjust the size of a raster background image

I'm attempting to apply a background image to a canvas element using a script tag at the bottom of my HTML file. When I execute this code, it renders a scaled-down version - essentially just one tile - of the original image. The canvas processing in ...

Ways to transform a Vue-wrapped object into a standard object

I am trying to set the data variable of type object to a normal variable const myVue = new Vue({ el: '#myVue', data: { vars: {}, // show Form }, methods: { assign_vars() { const new_vars = this.vars; }, }, }); html ...

What is causing ui-route to fail in resolving state1 when transitioning from state2?

I have a program that consists of two views (lefthandmenu and content), with modules. When the user selects a module from a combo-list, $state.go() is called with the selected module name, and the views should update accordingly. See code samples below. I ...

Tips for successfully passing slots to a Vue.js component instance that is created programmatically

My application necessitates the creation of dynamic component instances, and to achieve this, I have been utilizing the following approach: import Button from 'Button.vue' ... var Ctor = Vue.extend(Button); var instance = new Ctor({ propsData: { ...

A guide on retrieving the upload status of a file using an AJAX post request

Is there a way to retrieve the status of uploaded files when the user cancels the process while uploading multiple files using an ajax call? This is how I am currently making the ajax request to upload files: var request = $.ajax({ url: 'file ...

Obtain the user's profile picture and share it within the channel

delicious.on('message', msg => { if(!msg.guild) return; if(msg.content === 'wtfava') { msg.channel.send(msg.author.avatarURL) } }); Is there a way to retrieve the user's avatar URL when they use the command ...

How can JavaScript pass a variable through the URL?

I am attempting to pass a variable through the URL: http://localhost/new_wiki/test.php?id=http://example.com In my code, I have var first = getUrlVars()["id"];. This line is supposed to pass the value but it doesn't seem to be working. Can someone pl ...

Transform **kerry James O'keeffe-martin** into **Kerry James O'Keeffe-Martin** using TypeScript and Java Script

Is there a way to capitalize names in both TypeScript and JavaScript? For example, changing kerry James O'keeffe-martin to Kerry James O'Keeffe-Martin. ...

How can I show a loading screen while making a synchronous AJAX call in Chrome?

Is there any method to show a loading screen in Chrome while using async:false in an AJAX call? The use of setTimeout poses several challenges when making multiple synchronous AJAX calls within the setTimeout function. Additionally, the loading indicator ...

No information is being emitted by the subject

In my application, I have a feature where users input data that needs to be validated in a form. Once the validation is successful, a button is enabled allowing the user to submit their order. However, I'm facing an issue with this specific component ...

Overlaying a Bootstrap Collapse onto an element

I have been working with Bootstrap 3 to create a responsive website, specifically focusing on my "portfolio." You can view the website and also see an interesting error by visiting this link: If you scroll down to the section labeled "Our models" and cli ...

What is the process for defining the 'min' attribute for a date Textfield in Material UI?

Is it possible to set the minimum attribute for the date input field in Material UI? I know it's possible for the Input type date, but can it also be done for the Textfield type date? The code snippet provided below does not seem to be functioning pro ...

tips for optimizing javascript file caching

https://i.stack.imgur.com/UhWD1.pngMy web application was created using "pug" technology about 9-8 years ago, and more recently, pages have been added in an innovative framework (vue.js). However, whenever there is a transition between an old pug page and ...

AngularJS single-page application with model-view-controller style designs

Hey there, I'm relatively new to AngularJS and currently on a steep learning curve. I've been working on developing an AngularJS SPA and have grasped the basics. I'm using ngRoute for routing and have put together a basic application framew ...

How can I optimize my Javascript applications for better search engine rankings?

Recently, I've been exploring the idea of implementing a fresh workflow process for web development. Yemoan, Grunt, and Bower in conjunction with AngularJS look promising as a solution for front-end development. However, one major drawback is their po ...

Troubleshooting Multer to fix image payload issues in a Node.js and React.js application

Currently, I am facing an issue while trying to send an image from my ReactJS frontend to my NodeJS Express backend using formData. Despite seemingly correct data transmission, the image does not appear in the payload and triggers this error from the backe ...

I am facing an issue where I am unable to display the data received from axios response.data in

I am completely new to this, and my question may seem simple, but I haven't been able to find a solution yet. It's really important for me to figure this out. I've been trying to retrieve data from a GitHub repository using a REST API, but I ...