aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/docs/src/plugins/loadersPlugin.ts
blob: 325d7f6796d5acae85495c5c637b78753c6ef7d6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
 * SPDX-FileCopyrightText: 2024 The Refinery Authors
 *
 * SPDX-License-Identifier: EPL-2.0
 */

import type { Plugin } from '@docusaurus/types';

export default function loadersPlugin(): Plugin {
  return {
    name: 'refinery-loaders-plugin',
    configureWebpack(config) {
      let svgoDisabled = false;
      const rules = [...(config.module?.rules ?? [])];
      rules.forEach((rule) => {
        // Compare with
        // https://github.com/facebook/docusaurus/blob/73016d4936164ba38d4b86ec2aa8c168b5904a21/packages/docusaurus-utils/src/webpackUtils.ts#L128-L166
        if (
          typeof rule !== 'object' ||
          rule === null ||
          !('test' in rule) ||
          !(rule.test instanceof RegExp) ||
          !rule.test.test('.svg') ||
          !('oneOf' in rule)
        ) {
          return;
        }
        const {
          oneOf: [svgLoader],
        } = rule;
        if (
          typeof svgLoader !== 'object' ||
          svgLoader === null ||
          !('use' in svgLoader) ||
          typeof svgLoader.use !== 'object' ||
          svgLoader.use === null ||
          !(0 in svgLoader.use)
        ) {
          return;
        }
        const {
          use: [loader],
        } = svgLoader;
        if (
          typeof loader !== 'object' ||
          loader === null ||
          !('options' in loader)
        ) {
          return;
        }
        loader.options = {
          ...(typeof loader.options === 'object' ? loader.options : {}),
          svgo: true,
          svgoConfig: {
            plugins: [
              {
                name: 'preset-default',
                params: {
                  overrides: {
                    removeTitle: false,
                    removeViewBox: false,
                    // Disable SVGO, because it interferes styling figures exported from Refinery with CSS.
                    inlineStyles: false,
                    cleanupIds: false,
                  },
                },
              },
            ],
          },
        };
        svgoDisabled = true;
      });
      if (!svgoDisabled) {
        throw new Error('Failed to disable SVGO.');
      }
      return {
        mergeStrategy: {
          'module.rules': 'replace',
        },
        module: {
          rules,
        },
      };
    },
  };
}