Error in Vue CLI when trying to include a background image with inline CSS, the file path

Just like many others, I am struggling to find the correct path...

referencing @/assets/drive.jpg

I have attempted: ~@/assets/drive.jpg, ~/assets/drive.jpg, @/assets/drive.jpg

When I directly input it into my CSS, it works fine. However, when I try to use it inline (for dynamic purposes), it does not allow me.

<div>
      class="hero-image"
      :style="{
          backgroundImage: `url('${imageUrl}')`,
          backgroundPosition: `${imagePosition}`
      }"
</div>

Answer №1

There's a specific reason why that method is ineffective.

@ serves as an alias that webpack recognizes, handling imported files and <style> blocks. However, when used as a string within a template, it does not function properly. This can also lead to images not being transferred from assets to the dist folder.

Regrettably, you may need to explore alternative approaches for achieving your goal. By elaborating on what you're trying to accomplish, you might receive more suitable suggestions.

One option is to place the images in the dist/assets directory in advance, then use relative paths in styles like so: /assets/drive.jpg.

If you have a fixed list of images to include, you can utilize require('./assets/drive.jpg') within the component or even inline them. Keep in mind that since this is performed at compile time, require(imageUrl) will not be feasible.

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

Ensuring complete type safety by passing an object literal as a function parameter to a TypeScript type with rigorous type validation

I have a script written in JavaScript that I am currently converting to TypeScript. The code I am working with includes the following: const shapes = []; shapes.push({ name: 'Circle', radius: 12 }); shapes.push({ name: 'Rectangle', wid ...

What methods can be employed to enhance the User interface further?

I recently started using typescript and decided to migrate an existing project to it. In my middleware functions, which are located in a separate file, I have the following function: const checkCampgroundOwnership = async ( req: Request, res: Response ...

Can a Python script be executed asynchronously in a TypeScript fashion?

Currently, I have a Python script that sends an http request to a microservice, and the request typically takes 3 seconds to complete. Here is a summary of my Python script: def main(): response = request_to_MS(url) # This part of the process doesn& ...

How can I create reactivity for this hook in Vue 3?

So here's the deal, I have this hook code snippet that goes like this: export const useOpeningHours = ( flight: Ref<FlightOption | null>, identifier: string, isEnabled?: boolean ) => { if (!flight.value) { return { show: fa ...

What advantages does using an RxJS Subject have over handling multiple event listeners individually in terms of speed

After investigating a page's slow performance, I identified an angular directive as the root cause. The culprit was a piece of code that registered event listeners on the window keydown event multiple times: @HostListener('window:keydown', ...

What is the best way to implement a required input field in Vue.js?

I need some assistance with my chat functionality. I want to prevent users from sending empty messages, so I want to make the input field required. Can you please help me with this? I have already tried adding "required='required'" to the input ...

Error in nodejs typescript multer S3 upload - Cannot read map properties of undefined

I've created a route to upload files to an S3 bucket, and it's working perfectly. However, when I try to integrate it into my Accommodation controller with additional logic, I'm getting the error Cannot read properties of undefined (reading ...

The concept of Nested TypeScript Map Value Type

Similar to Nested Typescript Map Type, this case involves nesting on the "value" side. Typescript Playground const mapObjectObject: Map<string, string | Map<string, string>> = new Map(Object.entries({ "a": "b", &quo ...

How can I use Angular 4 typescript to deactivate a button based on the value of a boolean variable?

I am looking to define a function in TypeScript called 'isActive()', which I will then invoke on a button within my HTML file. Additionally, I have already declared a boolean variable named 'isActive'. In this scenario, I have two butto ...

Transitioning the height of a Vue component when switching routes

I've been struggling to implement a transition slide effect on my hero section. The height of the hero is set to 100vh on the homepage and half of that on other pages. Despite trying various methods, I haven't been able to get it working properly ...

An issue has occurred: the function cannot be applied to the intermediate value that is currently being processed

I am currently working on an Angular 5 CRUD application, utilizing Google Firebase services. I have been following a helpful video tutorial on YouTube (link here), but I encountered this error ngOnInit() { var x = this.employeeService.getData(); x.sna ...

Using 'import' and 'export' in Ionic 2 requires specifying 'sourceType: module'

Starting a new project using Ionic 2 and encountering an error after installing angular2-jwt: ParseError: 'import' and 'export' may appear only with 'sourceType: module' D:\desenv\arquivos\workspace_inbit&bsol ...

Creating dynamic components in Vue.js using VueJS and jQuery synergistically

New to Vue.js and in the process of building a Vue component inspired by this custom select menu. I want to include an ionicon with each list item. Typically, I can add the icon in Vue.js using: <component class="icon" :is="name-of-icon& ...

The combination of Next.JS and React Objects is not acceptable as a React child

Summary: Encountering the error Error: Objects are not valid as a React child (found: [object Promise]) while making a fetch request in a Typescript project. Interestingly, the same code snippet works without errors in a Javascript project. Recently, I ...

Encountering an issue with the ternary operation: Receiving the error message "Expected 0 arguments, but received

Encountering an issue in this function: prepareTickerIn(value: any){ let valueToReturn = ''; value.map((item,i,arr) => { valueToReturn += (arr.length-1 == i) ? (i==0 ? item.id : 'tickerId.in='+item.id) : ...

The data type 'string | number | boolean' cannot be assigned to type 'undefined'. Specifically, the type 'string' is incompatible with type 'undefined'. Error code: ts(2322)

When attempting to create a partial object with specific fields from a full object that meet certain criteria, I encountered a TypeScript error message. To better explain this issue, I designed a test module to showcase the concept/problem without using ac ...

Display a list of items using *ngFor in a dropdown menu without using the optgroup

Is there a way to group data from *ngFor in the dropdown selection without using optGroup? You can find the JSON file link below: JSON Data Typescript Code getProducts() { if (this.products.length < 1) { this.productService.getProducts ...

Creating a type definition for a TypeScript InfiniteScroll component in React

I am currently in the process of developing an InfiniteScroll component to be used like this: import { getData } from 'api'; import { InfiniteScroll } from 'components'; export const App = () => ( <InfiniteScroll fetcher={page ...

Converting Promises to Observables

Struggling with the syntax as I delve into learning Angular, I need to transform a promise into an Observable. Let me share what I've encountered: In the function getCountries (subscribed by another utility), there is a call required to fetch a list ...

While the router Link successfully generates the correct URL, it is failing to redirect to the component and display the data as intended

While working on my angular 7 app, I encountered an issue when navigating to the component report details. When using router link, it only creates a URL in the browser but does not actually redirect until I click Enter. The routing works correctly only i ...