I want to inline contents of a file (which is generated SVG sprite) into an HTML. I could use fs.readFileSync
as described here and then embed contents in dom, is it how people do it?
I also do not know how to correctly insert the contents of svg sprites, but ...
Embedding using client-javascript can help you?
https://github.com/jonathantneal/svg4everybody
I've been using it for a long time, and it helped me
You can use https://github.com/albinotonnina/parcel-plugin-inlinesvg or use fs.readFileSync
you can change the extension to .html
and it will work
also I clean the .svg
with the npm tool svgo
and magicly I can import the .svg
like regular html
file
svgr is pretty nifty too if you're using React:
yarn add @svgr/parcel-plugin-svgr
import MyIcon from 'my-icon.svg'
<MyIcon />
Also if you're running Typescript add a following type declaration to suppress errors on importing .svg
s:
// svg-shim.d.ts
declare module '*.svg' {
const content: any
export default content
}
For future readers: the shim file in @epiphone's comment was all I needed to get import working.
Update: I just noticed that I have received some downvotes. I'm not sure why. In case it's due to lack of clarity, let me elaborate a little. I just meant to point out that I found that the very last part of epiphone's solution is all you really need to get SVGs working (the svg-shim.d.ts
bit). The first part (installing the svgr plugin) is optional.
We can use PostHTML with Parcel: https://parceljs.org/html.html#posthtml. Just add https://github.com/andrey-hohlov/posthtml-inline-svg, and here it is, SVG gets inlined.
Install it: npm i -D posthtml-inline-svg
Add config:
// posthtml.config.js
module.exports = {
plugins: {
'posthtml-inline-svg': {
cwd: './src/icons',
},
},
};
And add this into your HTML:
<icon src="path/to/icon.svg"></icon>
Most helpful comment
svgr is pretty nifty too if you're using React:
yarn add @svgr/parcel-plugin-svgr
import MyIcon from 'my-icon.svg'
<MyIcon />
Also if you're running Typescript add a following type declaration to suppress errors on importing
.svg
s: