【问题标题】:How do I use .babelrc to get babel-plugin-import working for antd?如何使用 .babelrc 让 babel-plugin-import 为 antd 工作?
【发布时间】:2017-05-17 21:06:46
【问题描述】:

我是 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 中创建了一个,但也没有用。

代码 sn-p 应该去哪里?

https://github.com/ant-design/babel-plugin-import 的底部写着

如果您在其中添加库,babel-plugin-import 将无法正常工作 webpack 配置供应商。

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

我在这里问了另一个问题:How to get antd working with app created via create-react-app? 也许这个问题与我通过 create-react-app 创建的项目有关??

【问题讨论】:

    标签: babeljs create-react-app antd


    【解决方案1】:

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

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

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

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

    然后弹出你的应用:npm run eject

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

    打开这些文件并找到您需要插入 plugins 属性的位置,如说明页面中所述。

    【讨论】:

    • 成功了,谢谢!我不知道“在 create-react-app 中使用”部分,我仍然停留在“入门”。
    • 随着升级到 CRA 2.0,这又是一个问题! :(
    【解决方案2】:

    只需添加 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"
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-18
      • 1970-01-01
      • 2021-05-05
      • 2020-11-25
      • 2020-09-29
      • 2018-09-17
      • 2020-01-03
      相关资源
      最近更新 更多