8
8
import { getFileLoaderUtils } from '@docusaurus/utils' ;
9
9
10
10
import type { SVGRConfig , SVGOConfig } from './options' ;
11
- import type { RuleSetRule } from 'webpack' ;
11
+ import type { Configuration , RuleSetRule } from 'webpack' ;
12
12
13
13
// TODO Docusaurus v4: change these defaults?
14
14
// see https://github.com/facebook/docusaurus/issues/8297
@@ -37,7 +37,7 @@ const DefaultSVGRConfig: SVGRConfig = {
37
37
38
38
type Params = { isServer : boolean ; svgrConfig : SVGRConfig } ;
39
39
40
- function createSVGRLoader ( params : Params ) : RuleSetRule {
40
+ function createSVGRRule ( params : Params ) : RuleSetRule {
41
41
const options : SVGRConfig = {
42
42
...DefaultSVGRConfig ,
43
43
...params . svgrConfig ,
@@ -48,22 +48,42 @@ function createSVGRLoader(params: Params): RuleSetRule {
48
48
} ;
49
49
}
50
50
51
- export function createLoader ( params : Params ) : RuleSetRule {
51
+ export function enhanceConfig ( config : Configuration , params : Params ) : void {
52
52
const utils = getFileLoaderUtils ( params . isServer ) ;
53
- return {
53
+
54
+ const rules = config ?. module ?. rules as RuleSetRule [ ] ;
55
+
56
+ const existingSvgRule : RuleSetRule = ( ( ) => {
57
+ const rule = rules . find (
58
+ ( r ) => String ( r . test ) === String ( utils . rules . svgs ( ) . test ) ,
59
+ ) ;
60
+ if ( ! rule ) {
61
+ throw new Error (
62
+ "Docusaurus built-in SVG rule couldn't be found. The SVGR plugin can't enhance it." ,
63
+ ) ;
64
+ }
65
+ return rule ;
66
+ } ) ( ) ;
67
+
68
+ const newSvgRule : RuleSetRule = {
54
69
test : / \. s v g $ / i,
55
70
oneOf : [
56
71
{
57
- use : [ createSVGRLoader ( params ) ] ,
72
+ use : [ createSVGRRule ( params ) ] ,
58
73
// We don't want to use SVGR loader for non-React source code
59
74
// ie we don't want to use SVGR for CSS files...
60
75
issuer : {
61
76
and : [ / \. (?: t s x ? | j s x ? | m d x ? ) $ / i] ,
62
77
} ,
63
78
} ,
64
- {
65
- use : [ utils . loaders . url ( { folder : 'images' } ) ] ,
66
- } ,
79
+ existingSvgRule ,
67
80
] ,
68
81
} ;
82
+
83
+ // This is annoying, but we have to "wrap" the existing SVG rule
84
+ // Adding another extra SVG rule (first or last) will not "override"
85
+ // the default: both rules will be applied (from last to bottom) leading to
86
+ // conflicting behavior.
87
+ const index = rules . indexOf ( existingSvgRule ) ;
88
+ rules [ index ] = newSvgRule ;
69
89
}
0 commit comments