Search code examples
reactjswebpackcreate-react-app

Add Webpack Alias With react-app-rewired and customize-cra


I am trying to reduce the size of the Ant Design library by eliminating unnecessary icons. I found this solution online, https://github.com/ant-design/ant-design/issues/12011#issuecomment-423173228

The solution involves configuring Webpack like this:

module.exports = {
  //...
  resolve: {
    alias: {
      "@ant-design/icons/lib/dist$": path.resolve(__dirname, "./src/icons.js")
    }
  }
};

I don't know how to do this because I am using react-app-rewired and customize-cra along with babel-plugin-import, so my "config-overrides.js" file looks like this, which is very different from the provided example.

const { override, fixBabelImports } = require('customize-cra');

module.exports = override(
    fixBabelImports('import', {
        libraryName: 'antd',
        style: 'css',
    }),
);

I am using the following dependencies:

"antd": "^3.14.1",
"babel-plugin-import": "^1.11.0",
"customize-cra": "^0.2.12",
"downshift": "^3.2.6",
"material-icons-react": "^1.0.4",
"react": "^16.8.3",
"react-app-rewired": "^2.1.0",
"react-dom": "^16.8.3",
"react-scripts": "^2.1.5",
"styled-components": "^4.1.3"

This looks very different from the example in the Github Issue. How do I add an alias to my "config-overrides.js" file?


Solution

  • use plugin addWebpackAlias of customize-cra

    /* global require, module, __dirname */
    const { override, fixBabelImports, addWebpackAlias } = require('customize-cra')
    const path = require('path')
    
    module.exports = override(
      fixBabelImports('import', {
        libraryName: 'antd',
        libraryDirectory: 'es',
        style: 'css',
      }),
      addWebpackAlias({
        ['@']: path.resolve(__dirname, 'src')
      })
    )