1 4
import babelLoader from 'babel-loader';
2
import { PartialConfig, ConfigItem } from '@babel/core';
3 4
import { merge } from 'lodash';
4 4
import path from 'path';
5
import API from '../../../API';
6

7
interface CustomOptions {
8
  reactPreset: boolean;
9
  usePlugins: any[];
10
  api: API;
11
}
12

13 4
function processPresets(presets: ConfigItem[], babel: any, react: boolean) {
14 4
  const remaxPresetIndex = presets.findIndex(
15 4
    preset => preset.file && preset.file.resolved.includes(`${path.sep}babel-preset-remax${path.sep}`)
16
  );
17

18 4
  const defaultOptions = {
19
    react,
20
    targets: {},
21
  };
22

23 4
  const existOptions = remaxPresetIndex !== -1 ? presets[remaxPresetIndex].options : {};
24

25 4
  const remaxPreset = babel.createConfigItem(
26
    [require.resolve('babel-preset-remax'), merge({}, defaultOptions, existOptions)],
27
    {
28
      type: `preset`,
29
    }
30
  );
31

32 4
  if (remaxPresetIndex === -1) {
33 4
    presets.unshift(remaxPreset);
34
  } else {
35 4
    presets[remaxPresetIndex] = remaxPreset;
36
  }
37

38 4
  return presets;
39
}
40

41 4
export default babelLoader.custom((babelCore: any) => ({
42 4
  customOptions({ reactPreset, usePlugins, api, ...loaderOptions }: CustomOptions) {
43 4
    return {
44
      custom: {
45
        reactPreset,
46
        usePlugins,
47
        api,
48
      },
49
      loader: loaderOptions,
50
    };
51
  },
52

53 4
  config(cfg: PartialConfig, { customOptions }: { customOptions: CustomOptions }) {
54 4
    const { reactPreset, api, usePlugins } = customOptions;
55 4
    const presets = processPresets(cfg.options.presets as ConfigItem[], babelCore, reactPreset);
56 4
    const config = {
57
      ...cfg.options,
58
      presets,
59 4
      plugins: [...(cfg.options.plugins || []), ...(usePlugins || [])],
60
    };
61

62 4
    if (api) {
63 4
      api.configBabel({ config });
64
    }
65

66 4
    return config;
67
  },
68
}));

Read our documentation on viewing source code .

Loading