17

我是react,babel和antd的新手。

我安装了 react 并使用 create-react-app 启动了一个项目。我安装了 antd (ant.design)。它建议使用 babel-plugin-import,所以我也安装了它。

如果我解释正确,babel-plugin-import 的使用文档说把它放在一个 .babelrc 文件中:

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

我很难让它工作。我的网络控制台仍然有警告:

您正在使用一整包的 antd,请使用 https://www.npmjs.com/package/babel-plugin-import来减少 app bundle 的大小。

我的项目目录中没有 .babelrc 文件,所以我创建了一个包含上述内容的文件并重新启动了我的服务器(npm start)。那没有用,所以我在 myProject/node_modules/babel_plugin_import 中创建了一个,但这也不起作用。

该代码片段应该去哪里?

https://github.com/ant-design/babel-plugin-import的底部它说

如果你在 webpack config vender 中添加库,babel-plugin-import 将不起作用。

但我不知道那是什么意思。

我在这里问了另一个问题:如何让 antd 使用通过 create-react-app 创建的应用程序? 也许这个问题与我通过 create-react-app 创建的项目有关?

4

2 回答 2

10

[ 2018-02-06 更新:答案仍然正确,但现在有更好的选择,那就是使用react-app-rewired. 这也记录在链接中。]

您需要按照https://ant.design/docs/react/use-with-create-react-app#Import-on-demand中的说明操作到 T。

您不应创建ant.babelrc文件或类似文件。使用 CRA 时,所有 babel 配置都在 webpack 配置文件中处理。

首先清理您创建的配置文件,并确保您已babel-plugin-import安装。

然后弹出您的应用程序:npm run eject

这将为您提供一个config包含 2 个用于开发/生产环境的 webpack 配置文件的文件夹。

plugins打开这些文件并按照说明页面中的说明找到需要插入属性的位置。

于 2017-05-18T08:50:23.147 回答
0

只需添加babel-plugin-import文档所说的内容,但请记住,如果您使用的是 CRA,则无法在不弹出项目的情况下直接更改 babel 配置。

如果您不想弹出,可以使用@craco/craco,并将 babel 配置放入其中,如下所示:

/* 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. */
    },
  },
};

不要忘记更改脚本(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"
}
于 2021-10-06T23:04:17.537 回答