Skip to content

Commit

Permalink
fix(defs): Extract defs from symbols
Browse files Browse the repository at this point in the history
  • Loading branch information
farnabaz committed Feb 7, 2019
1 parent cefaeb9 commit 7af91e5
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
17 changes: 14 additions & 3 deletions lib/svg.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,18 +41,29 @@ export async function optimizeSVG(name, content) {
export function convertToSymbol(name, content) {
const $data = content
.replace('<svg', `<symbol id="i-${name}"`)
.replace('</svg>', '</symbol>');
.replace('</svg>', '</symbol>')
.replace(/<defs>(.+)<\/defs>/, '')

return $data;
}

export function extractDefs(content) {
const $data = content
.match(/<defs>(.+)<\/defs>/);

return $data ? $data[1] : ""
}

export function isSVGFile(file) {
return file.match(/.*\.svg$/);
}

export function wrap(content) {
export function wrap(content, defs) {
return '<?xml version="1.0" encoding="UTF-8"?>\n'
+'<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n'
+ '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n'
+ '<defs>\n'
+ defs
+ '\n</defs>\n'
+ content
+ '\n</svg>';
}
10 changes: 9 additions & 1 deletion lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
convertToSymbol,
isSVGFile,
wrap,
extractDefs,
} from './svg'

const logger = consola.withScope('@nuxtjs/svg-sprite')
Expand All @@ -30,11 +31,13 @@ async function newIcon(file, sprite, name) {
const raw_content = await readSVG(file)
const optimize_content = await optimizeSVG(name, raw_content)
const symbol = await convertToSymbol(name, optimize_content)
const defs = await extractDefs(optimize_content)

await registerSymbol(sprite, {
name,
path: file,
content: symbol,
defs
})
}

Expand Down Expand Up @@ -72,7 +75,12 @@ async function writeSprite(name, directory) {
.map(s => s.content)
.join('\n')

const svg = wrap(symbols)
let defs = Object.values(sprites[name].symbols)
.map(s => s.defs)
.filter(d => Boolean(d))
.join('\n')

const svg = wrap(symbols, defs)

await writeSVG(
join(directory, `${name}.svg`),
Expand Down

0 comments on commit 7af91e5

Please sign in to comment.