How do I use .babelrc to get babel-plugin-import working for antd?

Viewed 13635

I'm new to react, babel, and antd.

I installed react and started a project using create-react-app. I installed antd (ant.design). It suggests using babel-plugin-import, so I installed that too.

If I interpret it right, the usage documentation for babel-plugin-import says to put this in a .babelrc file:

{
  "plugins": [
    ["import", {
      "libraryName": "antd",
      "style": true
    }]
  ]
}

I'm having trouble getting it to work. My web console still has the warning:

You are using a whole package of antd, please use https://www.npmjs.com/package/babel-plugin-import to reduce app bundle size.

I didn't have a .babelrc file in my project's directory, so I created one with the above contents and restarted my server (npm start). That didn't work, so I created one in myProject/node_modules/babel_plugin_import but that doesn't work either.

Where is that code snippet supposed to go?

At the bottom of https://github.com/ant-design/babel-plugin-import it says

babel-plugin-import will be not working if you add the library in webpack config vender.

But I don't know what that means.

I asked another question here: How to get antd working with app created via create-react-app? Maybe this problem has something to do with my project created via create-react-app??

2 Answers

Just add what babel-plugin-import documentation says, but remember if you're using CRA, you cannot change babel configuration directly without ejecting the project.

If you don't want to eject, you can use @craco/craco, and put the babel configuration inside of it like this:

/* craco.config.js */

module.exports = {
  babel: {
    presets: [],
    plugins: [
      [
        "import",
        {
          libraryName: "antd",
          style: true, // or 'css'
        },
      ],
    ],
    loaderOptions: {
      /* Any babel-loader configuration options: https://github.com/babel/babel-loader. */
    },
  },
};

Dont forget to change your scripts (more details in craco docs):

/* package.json */

"scripts": {
-   "start": "react-scripts start",
+   "start": "craco start",
-   "build": "react-scripts build",
+   "build": "craco build"
-   "test": "react-scripts test",
+   "test": "craco test"
}
Related