0

I have a Vue app where I want to access some image files in an included JS file for various purposes, e.g. one of which is adding images to a canvas element.

This would normally be easy using something like the following:

function getImage() {
  let img = new Image();
  img.src = '/assets/images/bg.jpg';
  img.onload = function () {
    //
  };
}

I can technically access images in my public folder this way, but what if I want to access compiled image assets from my src folder rather than public folder?

In CSS I can simply use an @ symbol in the path like @/assets/images/bg.jpg (as this is configured as an alias in the vue config) so I tried...

img.src = '@/assets/images/bg.jpg';

...but this doesn't work.

Is there a way to achieve this, or is what I'm trying not possible? Perhaps assets referenced purely in JS aren't included in the build process? Thanks

3
  • Usually you don't want to put images in the src directory, as that gets 'compiled' into your bundle. Could you not put the assets within public? Commented Apr 12, 2022 at 16:26
  • @Lissy93 if it's the only option then yeah, I just normally have my image assets in src - it's useful if any get updated as when building they get given unique file names etc. Commented Apr 12, 2022 at 16:32
  • Did either of the below answers help? If so, you should accept one, and if not, you should specify more details as to what's still not working. Commented May 3, 2022 at 12:31

2 Answers 2

1

Tried this out, and it does in fact work.

<img src="@/assets/my-image.png" />

However since this is compiled, you won't be able to set / change the image src dynamically with JS like you're doing in your example above.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, this works in CSS and inline HTML, but not in JS unfortunately - looks like what I wanted may not be possible.
0

With webpack you can do this:

img.src = require('@/assets/images/bg.jpg');

During the build it will be replaced with a path to the compiled asset.

1 Comment

This results in the error Uncaught ReferenceError: require is not defined I guess Vue is limited to only ES module imports.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.