Skip to content

Commit dfe6a41

Browse files
authored
build(webpack): inline SVGs into CSS code (#50)
1 parent be370f5 commit dfe6a41

File tree

1 file changed

+32
-16
lines changed

1 file changed

+32
-16
lines changed

packages/react-scripts/config/webpack.config.js

Lines changed: 32 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -436,29 +436,45 @@ module.exports = function (webpackEnv) {
436436
},
437437
{
438438
test: /\.svg$/,
439-
use: [
439+
oneOf: [
440+
// Transform SVG into a React component when imported from JavaScript/TypeScript/Markdown files.
440441
{
441-
loader: require.resolve('@svgr/webpack'),
442-
options: {
443-
prettier: false,
444-
svgo: false,
445-
svgoConfig: {
446-
plugins: [{ removeViewBox: false }],
442+
issuer: { and: [/\.(ts|tsx|js|jsx|md|mdx)$/] },
443+
use: [
444+
{
445+
loader: require.resolve('@svgr/webpack'),
446+
options: {
447+
prettier: false,
448+
svgo: false,
449+
svgoConfig: {
450+
plugins: [{ removeViewBox: false }],
451+
},
452+
titleProp: true,
453+
ref: true,
454+
},
447455
},
448-
titleProp: true,
449-
ref: true,
450-
},
456+
{
457+
loader: require.resolve('file-loader'),
458+
options: {
459+
name: 'static/media/[name].[hash].[ext]',
460+
},
461+
},
462+
],
451463
},
464+
// Fallback: Inline SVG as a url-encoded data URL for all other imports.
452465
{
453-
loader: require.resolve('file-loader'),
454-
options: {
455-
name: 'static/media/[name].[hash].[ext]',
466+
type: 'asset/inline',
467+
generator: {
468+
dataUrl: content => {
469+
// Convert the raw SVG content to a UTF-8 encoded data URL.
470+
const svgString = content.toString();
471+
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(
472+
svgString
473+
)}`;
474+
},
456475
},
457476
},
458477
],
459-
issuer: {
460-
and: [/\.(ts|tsx|js|jsx|md|mdx)$/],
461-
},
462478
},
463479
{
464480
test: /\.(js|mjs|jsx|ts|tsx)$/,

0 commit comments

Comments
 (0)