Skip to content

Commit

Permalink
fix(module-tools): should not remove SVG viewBox attribute (#5322)
Browse files Browse the repository at this point in the history
  • Loading branch information
chenjiahan authored Jan 29, 2024
1 parent c937d0c commit 48e52e3
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 2 deletions.
7 changes: 7 additions & 0 deletions .changeset/tall-elephants-cross.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@modern-js/module-tools': patch
---

fix(module-tools): should not remove SVG viewBox attribute

fix(module-tools): 避免移除 SVG viewBox 属性
27 changes: 25 additions & 2 deletions packages/solutions/module-tools/src/builder/feature/asset.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { basename, join, extname, relative, dirname, resolve } from 'path';
import fs from 'fs';
import _ from '@modern-js/utils/lodash';
import type { Loader } from 'esbuild';
import { createFilter } from '@rollup/pluginutils';
import { transform } from '../../../compiled/@svgr/core';
import svgo from '../../../compiled/@svgr/plugin-svgo';
import jsx from '../../../compiled/@svgr/plugin-jsx';
import { ICompiler } from '../../types';
import type { ICompiler, SvgrOptions } from '../../types';
import { assetExt } from '../../constants/file';
import { normalizeSlashes, getHash } from '../../utils';

Expand Down Expand Up @@ -58,6 +59,25 @@ function encodeSVG(buffer: Buffer) {
);
}

const getDefaultSVGRConfig = (): SvgrOptions => ({
svgo: true,
svgoConfig: {
plugins: [
{
name: 'preset-default',
params: {
overrides: {
// viewBox is required to resize SVGs with CSS.
// @see https://github.com/svg/svgo/issues/1128
removeViewBox: false,
},
},
},
'prefixIds',
],
},
});

/**
*
* @param this Compiler
Expand Down Expand Up @@ -92,7 +112,10 @@ export async function getAssetContents(
let contents: string | Buffer = normalizedPublicPath;
let loader: Loader = 'text';

const config = typeof svgr === 'boolean' ? {} : svgr;
const defaultConfig = getDefaultSVGRConfig();
const config =
typeof svgr === 'boolean' ? defaultConfig : _.merge(defaultConfig, svgr);

const filter = createFilter(config.include || SVG_REGEXP, config.exclude);
if (svgr && filter(assetPath)) {
// svgr jsx-loader
Expand Down
2 changes: 2 additions & 0 deletions tests/integration/module/fixtures/build/asset/asset.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ describe('asset.svgr', () => {
const distFilePath = path.join(fixtureDir, './dist/bundle/index.js');
const content = await fs.readFile(distFilePath, 'utf-8');
expect(content.includes(`jsx("svg"`)).toBeTruthy();
// should not remove SVG viewBox attribute
expect(content.includes('viewBox: "0 0 841.9 595.3"')).toBeTruthy();
});
it('bundleless', async () => {
const configFile = 'bundleless.config.ts';
Expand Down

0 comments on commit 48e52e3

Please sign in to comment.