Created
May 6, 2022 08:33
-
-
Save Excalibaard/5ec706565788ed9c118e08794b28149c to your computer and use it in GitHub Desktop.
SVGO + Vue inline SVG loader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { optimize, loadConfig } = require('svgo'); | |
const { getOptions } = require('loader-utils'); | |
async function loader(svg) { | |
const { configFile, ...options } = getOptions(this) || {}; | |
let config; | |
if (typeof configFile === 'string') { | |
config = await loadConfig(configFile, this.context); | |
} else if (configFile !== false) { | |
config = await loadConfig(null, this.context); | |
} | |
const result = optimize(svg, { | |
path: this.resourcePath, | |
...config, | |
...options, | |
}); | |
if (result.error) throw Error(result.error); | |
return `<template>${result.data}</template>`; | |
} | |
module.exports = function(svg) { | |
const callback = this.async(); | |
loader | |
.call(this, svg) | |
.then(result => callback(null, result)) | |
.catch(error => callback(error)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@dschrul Not yet, I used this in enterprise code for a company I don't work at anymore. I'll see when I have the time to make a sample project. but won't make any promises.
I made this gist before I realized it could be a lot simpler though. This gist replaces the entire
vue-svg-loader
functionality, which is two steps:<template>
tags (sovue-loader
in the next step will interpret the input as a Vue component)But, Webpack loaders are made to be chained. Instead of this gist, I suggest you use two loaders, one for each process.
The first step can use svgo-loader which is actively maintained by the svgo team. The second step is one line of code (see line 22 of this gist), which is too small to have as a dependency IMO (remember leftpad). Instead, you can add your own loader. I described the process of adding your own loader in this post below.
damianstasik/vue-svg-loader#156 (comment)
Here's an example of what it could look like in your project (modified from the comment above). It avoids
resolveLoader
, though I only recommend this if you're not expecting to use more custom loaders.Then import SVGs like: