Gilian
Gilian

Reputation: 1599

Changing the assets directory in Vue

I'm working on a project that was created using the vue cli 3.0. And on creation a src/assets folder is also made. This folder can include some images for example.

Is it possible to change the path of the assets to something different?

I tried changing the assetsDir setting in vue.config.js. But this only changes the output path in the build.

Edit:

I should note that I would like to load assets based on a "vendor" environment variable. So if I set this to vendorX it should load src/assets/vendorX and with vendorY it should load src/assets/vendorY.

Edit 2:

It appears that the directory name doesn't matter to the Vue Cli. I changed the assets folder name to vendors. But my guess is that Vue includes all resources files in src by default. So I'm now looking for a way to change this, or maybe find a different solution.

Upvotes: 1

Views: 3013

Answers (2)

Valentine Shi
Valentine Shi

Reputation: 7800

This is how to access an asset in the arbitrary folder from your Vue SFC / template files using webpack alias.

Assume you have the following line in some of your SFC:

<!-- I would like to access the logo that is located at the  -->
<!-- "project root/public/assets/images/" -->
<img alt="Vue logo" src="@public/assets/images/logo.png" />

Then in your vue.config.js have the following code:

const { defineConfig } = require('@vue/cli-service');
const path = require('path');

module.exports = defineConfig({
    transpileDependencies: true,
    configureWebpack: {
        resolve: {
            alias: {
                '@src': path.join(__dirname, 'src'),
                '@public': path.join(__dirname, 'public')
            }
        }
    }
})

The alias key is where you configure the aliases. Refer for the details on Vue CLI webpack configuration to its official docs.

The aliases defined here can be also used from your JS files.

Upvotes: 0

nicktu12
nicktu12

Reputation: 129

If the assets folder was setup with an alias, that would be found in webpack.config, however the vue-cli appears to create a project with hardcoded paths to the assets. Try changing the src path for your assets across all files to ./assetsDir/myImg.png.

Upvotes: 2

Related Questions