alvinometric / remark-inline-svg

Plugin that inlines SVG images from markdown and optimises them with svgo
MIT License
3 stars 1 forks source link
minification remark remark-plugin svg

remark-inline-svg

Downloads Size version MIT License

Plugin that takes SVG images in markdown, optimises them with SVGO and adds them inline to the HTML output.

Installation

Install

This package is ESM only. In Node.js (version 12.20+, 14.14+, 16.0+, or 18.0+), install with npm:

npm install remark-inline-svg

In Deno with esm.sh:

import inlineSVG from 'https://esm.sh/remark-inline-svg@1';

In browsers with esm.sh:

<script type="module">
  import inlineSVG from 'https://esm.sh/remark-inline-svg@1?bundle';
</script>

Usage

Say we have the following file example.md:

# Hello

This is a test markdown document.

![Inline SVG](circle.inline.svg)

Cheers

And our module example.js looks as follows:

import { remark } from 'remark';
import inlineSVG from 'remark-inline-svg';
import { readSync } from 'to-vfile';

const file = readSync('./example.md');

remark()
  .use(inlineSVG)
  .process(file, function (err, file) {
    if (err) throw err;
    console.log(String(file));
  });

Now running node example.js yields:

# Hello

This is a test markdown document.

<figure class="markdown-inline-svg">
  <svg fill="none" viewBox="0 0 250 250" role="img" aria-hidden="true"><circle cx="125" cy="125" r="100" fill="#BA5B5B"/></svg>
</figure>

Cheers

Options

Key Default value Description
suffix ".inline.svg" The plugin only processes SVG files ending with this value
replace undefined Lets you replace strings within the SVG file
className markdown-inline-svg class of the wrapper element

suffix

This plugin will ignore SVG files if they don't have the specified suffix, set to .inline.svg by default. This is to minimise disruption to your workflow.

replace

Array of strings to replace with other strings, for example:

{
  replace: {
    "#41DE50": "currentColor"
  }
}

Then #41DE50 will be replaced with currentColor in the SVG output.

className

The inlined SVG is wrapped in a <figure> element, and given a class of markdown-inline-svg to let you apply some custom styles. You can change that class by modifiying the value of the className option.

<!-- You can change this class name 👇 -->
<figure class="markdown-inline-svg">
  <svg fill="none" viewBox="0 0 250 250" role="img" aria-hidden="true">
    <circle cx="125" cy="125" r="100" fill="#BA5B5B" />
  </svg>
</figure>

SVGO configuration

The SVGO configuration is as follows:

const svgoPlugins = [
  {
    name: 'preset-default',
    params: {
      overrides: {
        // disable plugins
        removeTitle: false,
        removeDesc: false,
      },
    },
  },
  'removeXMLNS',
  'removeDimensions',
  'sortAttrs',
];

TODO: