I have a Vue 2 sample project at
I did try:
data() {
return{
cloudSvg: require('./TheCloud.svg')
}
},
But that did not work and I see:
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.
yarn add raw-loader
- create a
vue.config.js
file at the root of the project with the following contents to configure theraw-loader
.
module.exports = {
chainWebpack: config => {
config.module
.rule('raw-loader')
.test(/\.txt$/i)
.use('raw-loader')
.loader('raw-loader')
.end()
}
}
- 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.
- 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:
- move
TheCloud.svg
to thepublic/
folder. - 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.