Home > Blockchain >  How can I load a SVG directly instead of importing via a js file for use in a leaflet divIcon?
How can I load a SVG directly instead of importing via a js file for use in a leaflet divIcon?

Time:07-06

I have a Vue 2 sample project at working image

I did try:

  data() {
    return{
      cloudSvg: require('./TheCloud.svg')
    }
  },

But that did not work and I see:

not working

Is there a way to do this? I would like to avoid the extra step of placing the SVG source inside of javascript files. It seems like this should be unnecessary.

CodePudding user response:

I found one method that is working, but I am sure there are ways to improve it.

The following changes are on the raw-loader branch.

  1. yarn add raw-loader
  2. create a vue.config.js file at the root of the project with the following contents to configure the raw-loader.
module.exports = {
  chainWebpack: config => {
    config.module
      .rule('raw-loader')
      .test(/\.txt$/i)
      .use('raw-loader')
        .loader('raw-loader')
        .end()
  }
}
  1. Changed my data() method to:
  data() {
    return{
      center: [37.781814, -122.404740],
      cloudSvg: require('./TheCloud.svg'),
      cloudSrc: require('./TheCloud.txt')
    }
  },

adding cloudSrc: require('./TheCloud.txt').

TheCloud.txt is a duplicate of TheCloud.svg, but with a different extension so the raw-loader will process it.

  1. Change the usage of divIcon to:
      const cloudIcon = L.divIcon({
        html: this.cloudSrc.default, // thecloud, // this.cloudSvg, // thecloud,
        className: 'my-custom-icons',
        iconSize: [size, size],
        iconAnchor: [size/2, size/2]
      })

I cannot say I understand everything going on here, like why I need the .default part or the webpack configuration section, but this is working.

CodePudding user response:

My preferred solution is to use what I am calling the fetch-method.

The changes I made was to:

  1. move TheCloud.svg to the public/ folder.
  2. use the fetch to obtain the svg source
const response = await fetch( "/TheCloud.svg");
const source = await response.text();

While embedding SVGs in the source code works well when there is just a single or a small number of SVGs, when the number of SVGs becomes large, I believe this method is among the best solutions.

I have updated the repo with the fetch-method implemented.

  • Related