Parcel: what's simplest way to Inline SVG into html?

Created on 26 Jun 2018  路  7Comments  路  Source: parcel-bundler/parcel

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?

Question

Most helpful comment

svgr is pretty nifty too if you're using React:

  1. install plugin: yarn add @svgr/parcel-plugin-svgr
  2. import svg: import MyIcon from 'my-icon.svg'
  3. use as any other component: <MyIcon />

Also if you're running Typescript add a following type declaration to suppress errors on importing .svgs:

// svg-shim.d.ts
declare module '*.svg' {
  const content: any
  export default content
}

All 7 comments

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 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:

  1. install plugin: yarn add @svgr/parcel-plugin-svgr
  2. import svg: import MyIcon from 'my-icon.svg'
  3. use as any other component: <MyIcon />

Also if you're running Typescript add a following type declaration to suppress errors on importing .svgs:

// 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>
Was this page helpful?
0 / 5 - 0 ratings

Related issues

jpsc picture jpsc  路  81Comments

jpergler picture jpergler  路  59Comments

Clickys picture Clickys  路  61Comments

shiloa picture shiloa  路  39Comments

natqe picture natqe  路  40Comments