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

feat: allow .svg files to be inlined #1716

Closed
wants to merge 1 commit into from
Closed
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
10 changes: 6 additions & 4 deletions packages/vite/src/node/plugins/asset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,11 +171,13 @@ async function fileToBuiltUrl(
let url
if (
config.build.lib ||
(!file.endsWith('.svg') &&
content.length < Number(config.build.assetsInlineLimit))
Buffer.byteLength(content) < config.build.assetsInlineLimit
) {
// base64 inlined as a string
url = `data:${mime.getType(file)};base64,${content.toString('base64')}`
// svgs can be inlined without base64
url = file.endsWith('.svg')
? `data:image/svg+xml;utf8,${content}`
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This won't escape unsafe characters. Might be worth taking a similar approach to svg-url-loader? See Explanation, Usage and Implementation.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The data uri has a mime type, so I'm skeptical that the "unsafe characters" specification applies here.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a URI, so yes you need to escape unsafe characters or it won't work.
E.g. for <path fill="#ffffff" />, the # starts the URL fragment and everything breaks, so it needs to be escaped to <path fill="%23ffffff" />

: // base64 inlined as a string
`data:${mime.getType(file)};base64,${content.toString('base64')}`
} else {
// emit as asset
// rollup supports `import.meta.ROLLUP_FILE_URL_*`, but it generates code
Expand Down