Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add support to overwrite svgo options #106

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,43 @@ module.exports = {
}
```

to overwrite SVGO options:

See list of configurable [built in plugins](https://github.com/svg/svgo#built-in-plugins). TAKE NOTE: the props name to configure SVGO plugins is called `features`

```js
module.exports = {
plugins: [
{
resolve: "gatsby-transformer-inline-svg",
options: {
multipass: true,
floatPrecision: 2,
features: [
{
name: 'preset-default',
params: {
overrides: {
removeViewBox: false
}
}
},
'cleanupListOfValues',
'prefixIds',
'removeDimensions',
'removeOffCanvasPaths',
'removeRasterImages',
'removeScriptElement',
'convertStyleToAttrs',
'reusePaths',
'sortAttrs'
],
},
}
]
}
```


**GraphQL Query**:
```graphql
Expand Down
106 changes: 99 additions & 7 deletions gatsby-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,84 @@ const defaultSVGOOptions = {
// do we really need this? :(
const sessionCache = {}

exports.pluginOptionsSchema = ({ Joi }) => {
return Joi.object({
multipass: Joi.boolean()
.default(true)
.description(
`Pass over SVGs multiple times to ensure all optimizations are applied. boolean. true by default`
),
floatPrecision: Joi.number()
.default(2)
.description(
`Set number of digits in the fractional part, overrides plugins params`
),
// plugins is a reserved props
features: Joi.array()
.items(
Joi.string().valid(
'cleanupAttrs',
'mergeStyles',
'inlineStyles',
'removeDoctype',
'removeXMLProcInst',
'removeComments',
'removeMetadata',
'removeTitle',
'removeDesc',
'removeUselessDefs',
'removeXMLNS',
'removeEditorsNSData',
'removeEmptyAttrs',
'removeHiddenElems',
'removeEmptyText',
'removeEmptyContainers',
'removeViewBox',
'cleanupEnableBackground',
'minifyStyles',
'convertStyleToAttrs',
'convertColors',
'convertPathData',
'convertTransform',
'removeUnknownsAndDefaults',
'removeNonInheritableGroupAttrs',
'removeUselessStrokeAndFill',
'removeUnusedNS',
'prefixIds',
'cleanupIds',
'cleanupNumericValues',
'cleanupListOfValues',
'moveElemsAttrsToGroup',
'moveGroupAttrsToElems',
'collapseGroups',
'removeRasterImages',
'mergePaths',
'convertShapeToPath',
'convertEllipseToCircle',
'sortAttrs',
'sortDefsChildren',
'removeDimensions',
'removeAttrs',
'removeAttributesBySelector',
'removeElementsByAttr',
'addClassesToSVGElement',
'addAttributesToSVGElement',
'removeOffCanvasPaths',
'removeStyleElement',
'removeScriptElement',
'reusePaths'
),
Joi.object({
name: Joi.string().description(`name of plugins`),
params: Joi.object().description(`additional plugins params options`)
})
)
.min(0)
.default(defaultSVGOOptions.plugins)
.description(`Set SVGO features/plugins`)
})
}

exports.createSchemaCustomization = ({ actions }) => {
actions.createTypes(`
type InlineSvg {
Expand All @@ -50,7 +128,7 @@ exports.createSchemaCustomization = ({ actions }) => {
`)
}

async function processSVG({ absolutePath, store, reporter }) {
async function processSVG({ absolutePath, store, reporter, svgomgOpts }) {
// Read local file
const svg = await fs.readFile(absolutePath, 'utf8')

Expand All @@ -61,9 +139,19 @@ async function processSVG({ absolutePath, store, reporter }) {
)
}

const { multipass, floatPrecision, features: plugins } = svgomgOpts || {}

const svgopts = svgomgOpts
? {
multipass,
floatPrecision,
plugins
}
: defaultSVGOOptions

// @ts-ignore
const result = optimize(svg.toString(), {
...defaultSVGOOptions,
...svgopts,
path: absolutePath
})

Expand Down Expand Up @@ -91,7 +179,7 @@ async function processSVG({ absolutePath, store, reporter }) {
)
}

async function queueSVG({ absolutePath, cache, store, reporter }) {
async function queueSVG({ absolutePath, cache, store, reporter, svgomgOpts }) {
const cacheId =
'contentful-svg-content-' +
crypto.createHash(`md5`).update(absolutePath).digest(`hex`)
Expand All @@ -113,7 +201,8 @@ async function queueSVG({ absolutePath, cache, store, reporter }) {
const processPromise = processSVG({
absolutePath,
store,
reporter
reporter,
svgomgOpts
})

sessionCache[cacheId] = processPromise
Expand All @@ -130,7 +219,10 @@ async function queueSVG({ absolutePath, cache, store, reporter }) {
})
}

exports.createResolvers = ({ cache, createResolvers, store, reporter }) => {
exports.createResolvers = (
{ cache, createResolvers, store, reporter },
svgomgOpts
) => {
createResolvers({
File: {
svg: {
Expand All @@ -143,7 +235,7 @@ exports.createResolvers = ({ cache, createResolvers, store, reporter }) => {
return null
}

return queueSVG({ absolutePath, store, reporter, cache })
return queueSVG({ absolutePath, store, reporter, cache, svgomgOpts })
}
}
},
Expand Down Expand Up @@ -171,7 +263,7 @@ exports.createResolvers = ({ cache, createResolvers, store, reporter }) => {
cache
})

return queueSVG({ absolutePath, store, reporter, cache })
return queueSVG({ absolutePath, store, reporter, cache, svgomgOpts })
}
}
}
Expand Down
53 changes: 52 additions & 1 deletion gatsby-node.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
const nock = require('nock')
const fs = require('fs-extra')

const { createResolvers } = require('./gatsby-node')
const { createResolvers, pluginOptionsSchema } = require('./gatsby-node')
const { testPluginOptionsSchema } = require('gatsby-plugin-utils')

const registeredResolvers = new Map()
const actualCacheMap = new Map()
Expand Down Expand Up @@ -84,6 +85,56 @@ describe('general', () => {
})
})

describe(`pluginOptionsSchema`, () => {
it(`should invalidate incorrect options`, async () => {
const options = {
multipass: undefined, // Should be a boolean
floatPrecision: '1112', // Should be a number
features: `not a boolean` // Should be an array
}

const { isValid } = await testPluginOptionsSchema(
pluginOptionsSchema,
options
)

expect(isValid).toBe(false)
})

it(`should validate correct options`, async () => {
const options = {
multipass: true,
floatPrecision: 2,
features: [
{
name: 'preset-default',
params: {
overrides: {
removeViewBox: false
}
}
},
'cleanupListOfValues',
'prefixIds',
'removeDimensions',
'removeOffCanvasPaths',
'removeRasterImages',
'removeScriptElement',
'convertStyleToAttrs',
'reusePaths',
'sortAttrs'
]
}
const { isValid, errors } = await testPluginOptionsSchema(
pluginOptionsSchema,
options
)

expect(isValid).toBe(true)
expect(errors).toEqual([])
})
})

describe('gatsby-source-filesystem', () => {
beforeEach(() => {
createResolversMock.mockClear()
Expand Down
29 changes: 15 additions & 14 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "gatsby-transformer-inline-svg",
"version": "1.2.0",
"version": "1.3.0",
"description": "Inline SVGs from any GraphQL source",
"main": "index.js",
"engines": {
Expand Down Expand Up @@ -43,30 +43,31 @@
]
},
"dependencies": {
"debug": "^4.1.1",
"fs-extra": "^11.0.0",
"gatsby-core-utils": "^3.9.1",
"debug": "^4.3.4",
"fs-extra": "^11.1.1",
"gatsby-core-utils": "^4.9.0",
"mini-svg-data-uri": "^1.4.4",
"p-queue": "^6.2.1",
"svgo": "^2.0.0"
"p-queue": "6.6.2",
"svgo": "^3.0.2"
},
"devDependencies": {
"@types/jest": "29.2.6",
"@types/svgo": "2.6.4",
"eslint": "8.32.0",
"@types/jest": "29.5.1",
"@types/svgo": "3.0.0",
"eslint": "8.39.0",
"eslint-config-react-app": "7.0.1",
"eslint-plugin-flowtype": "8.0.3",
"eslint-plugin-import": "2.27.5",
"eslint-plugin-jest": "27.2.1",
"eslint-plugin-jsx-a11y": "6.7.1",
"eslint-plugin-react": "7.32.1",
"eslint-plugin-react": "7.32.2",
"eslint-plugin-react-hooks": "4.6.0",
"gatsby": "4.25.3",
"gatsby": "5.9.0",
"gatsby-plugin-utils": "^4.9.0",
"husky": "8.0.3",
"jest": "29.3.1",
"lint-staged": "13.1.0",
"jest": "29.5.0",
"lint-staged": "13.2.2",
"nock": "13.3.0",
"prettier": "2.8.3"
"prettier": "2.8.8"
},
"peerDependencies": {
"gatsby": ">=4.9.0",
Expand Down
Loading