3

In my vue-cli project, I need to reference an svg-file in an <img>-tag. That works.

Now inside this svg file, I have an <image xlink:href="..."> – And this path is not touched or resolved by webpack.

Example:

<!-- MyComponent.vue -->
<img src="@/assets/someImage.svg" />

<!-- someImage.svg -->
<svg ...>
  <!-- none of these are working -->
  <image ... xlink:href="@/assets/arcade-bg-4.jpg"/>
  <image ... xlink:href="~@/assets/arcade-bg-4.jpg"/>
  <image ... xlink:href="./assets/arcade-bg-4.jpg"/>
  <image ... xlink:href="/src/assets/arcade-bg-4.jpg"/>
</svg>

The question now is, how I can tell webpack to solve paths inside this svg file?

Possible workarounds: * put arcade-bg-4.jpg in /public and reference this in the xlink:href * use inline-<svg> in MyComponent.vue

But I'd like to keep the <img />-tag and also keep the file-hashing feature from vue-cli.

Background: I use this setup to achieve a (relatively) cross-browser-ready clip-mask with a .jpg instead of a .png, which is way smaller and more performant.

katerlouis
  • 536
  • 6
  • 16

1 Answers1

1

You should be using just href instead of xlink:href in <image> of <svg>

or

You need to use require along with v-bind like so <image ... :href="require('@/assets/arcade-bg-4.jpg')" />

or

In case of webpack you will need to add this to vue-loader's options as either transformToRequire or transformAssetUrls according to the version

// webpack.config.js
module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          transformToRequire: {
           image: ['xlink:href', 'href']
          }
        }
      }
    ]
  }
}
zapping
  • 4,118
  • 6
  • 38
  • 56
  • 2
    Correct me if I’m wrong, but I don’t believe this will work unless you wrap your SVG as a vue component, which is undesirable. – Rúnar Berg Oct 02 '19 at 16:15
  • If you want to use the file hashing feature from Vue CLI then the SVG then it needs to be within the Vuejs app scope. – zapping Oct 03 '19 at 05:31
  • I thought the hashing feature was a feature of webpack. I was hoping there would be a webpack setting to replace the `href` attributes of `` and `` tags in standalone SVG files. – Rúnar Berg Oct 10 '19 at 20:24