egurb
egurb

Reputation: 1216

How to configure Vue CLI 3 to leverage webpack root folder aliases?

I am trying to link a static content (img) from the assets folder to a vue component, but receiving the "Module not found: Error: Can't resolve" error message.

When I link the image from the root component it resolves, however from other component, in subfolders the list is not resolved.

Please see the example below:

├── App.vue <-- src="./assets/logo.png" resolved
├── assets
│   └── logo.png
├── components
│   └── some-other-component.vue <-- src="./assets/logo.png" not resolved

I was trying to set an alias to the 'src' folder using the following Webpack configuration, in the vue.config.js, but no luck as well:

module.exports = {
  configureWebpack: {
    resolve: {
      alias: {
        "@": require("path").resolve(__dirname, "src")
      }
    }
  }
}

I wonder if there is any way of achieving this?

Upvotes: 4

Views: 2674

Answers (2)

Lu&#226;n Trương
Lu&#226;n Trương

Reputation: 61

They defined it here

URL Transform Rules If the URL is an absolute path (e.g. /images/foo.png), it will be preserved as-is.

If the URL starts with ., it's interpreted as a relative module request and resolved based on the folder structure on your file system.

If the URL starts with ~, anything after it is interpreted as a module request. This means you can even reference assets inside node modules:

If the URL starts with @, it's also interpreted as a module request. This is useful because Vue CLI by default aliases @ to /src. (templates only)

https://cli.vuejs.org/guide/html-and-static-assets.html#url-transform-rules

Upvotes: 1

dziraf
dziraf

Reputation: 3653

It's not being resolved in your some-other-component.vue because the path you are giving points to src/components/assets/logo.png instead of src/assets/logo.png Use either ../assets/logo.png or better: @/assets/logo.png

Upvotes: 0

Related Questions