Use BASE_URL in component’s JavaScript – Vue.js

You probably already know you can use BASE_URL in your HTML markup like this:

<link rel="manifest" href="<%= BASE_URL %>manifest.json">
Code language: HTML, XML (xml)

If you want to use it within JavaScript you can define a publicPath in your component's data like this:

data() { return { publicPath: process.env.BASE_URL, user: {}, }; },
Code language: JavaScript (javascript)

Then simply use it as a regular .vue file or template like any variable:

<img :src="`${publicPath}img/icon.svg`" alt="My Image">
Code language: HTML, XML (xml)

About Ricard Torres

Senior Front-end Software Engineer at Netcentric, from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

@ricard_dev @ricard_dev

📝 Blog 🎙 Podcast

Leave a Reply

Add <code> Some Code </code> if you need to.