reactjswebpackcreate-react-appreact-app-rewired

Override CRA webpack config without ejecting (remove random numbers from media files)


I need to remove generated random numbers from all pdf files names in my project. (for example license.pdf instead of license.3402bc5d.pdf)

I tried to use react-app-rewired.

file config-overrides.js:

module.exports = function override(config, env) {
  config.module = {
    ...config.module, // copy all settings
    rules: [
      ...config.module.rules,
      {
        oneOf: [
          {
            test:/\.pdf$/,
            loader: 'file-loader',
            options: { name: "static/media/[name].pdf"}
          }
        ]
      },
    ]
  };
  return config;
};

But it didn't work


Solution

  • Here is the solution:

    module.exports = function override(config, env) {
      config.module.rules[1].oneOf = config.module.rules[1].oneOf.map((one) => {
        if (one.options && one.options.name && one.exclude) {
          one.exclude = [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/, /\.pdf$/];
        }
        return one;
      }).concat([
        {
          test:/\.pdf$/,
          loader: 'file-loader',
          options: { name: "/docs/[name].[ext]"}
        }
      ]);
    
      return config;
    };