William Daniels
William Daniels

Reputation: 67

Get an svg file as text dynamically in Vue

Im using a library (leaflet) that requires html as string. I have svgs saved in assets. So far, here is my method

getSvg( file ) {
  try {
    const name = file.substr( 0, file.lastIndexOf( '.' ) )
    return require( `@/assets/icons/profile/${ name }.svg` )
  } catch ( e ) { 
    return null
  }
}

How am I able to get the svg element as a string from this? I have also tried doing this

'<img :src=${ svg }/>'

But that doesnt draw the svg

Upvotes: 1

Views: 1140

Answers (1)

tony19
tony19

Reputation: 138216

Use raw-loader to get the raw text of the SVG file:

  1. Install raw-loader

    npm install -D raw-loader
    
  2. Prefix the import path with !!raw-loader!, and get the default property of the imported value:

    return require( `!!raw-loader!@/assets/icons/profile/${ name }.svg` ).default
    

Upvotes: 3

Related Questions