const path = require('path');
const webpack = require('webpack');
const getEnvVars = require('../../../config/envVars');
const assetsPath = path.resolve(__dirname, '../src/assets/');

module.exports = ({ config, mode }) => {
  config.module.rules.push({
    test: /\.(ts|tsx)$/,
    use: [
      {
        loader: require.resolve('babel-loader'),
        options: {
          rootMode: 'upward',
        },
      },
    ],
  });

  config.module.rules.push({
    test: /\.mdx?$/,
    use: [
      'babel-loader',
      '@mdx-js/loader',
      path.join(__dirname, './fm-loader'),
    ],
  });

  // svg with @svgr
  const fileLoaderRule = config.module.rules.find((rule) =>
    rule.test.test('.svg'),
  );

  fileLoaderRule.test = /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|ttf|woff|woff2|cur|ani)(\?.*)?$/;

  config.module.rules.push({
    test: /\.svg$/,
    include: assetsPath,
    use: [
      {
        loader: '@svgr/webpack',
        options: {
          icon: true,
        },
      },
      'file-loader',
    ],
  });

  config.resolve.extensions.push('.ts', '.tsx');
  config.resolve.modules.push(path.resolve('../../node_modules'));
  config.resolve.alias['~'] = path.resolve('./src');

  // Load monorepo env variables, required to use the `shared` package
  config.plugins.push(new webpack.EnvironmentPlugin(getEnvVars()));

  config.node = {
    ...config.node,
    fs: 'empty',
  };

  return config;
};
