babel import多个插件的按需引入

  • 目标,同时配置antd和antd-mobile的按需引入

原本只引入了antd,如下是confing-overrides.js配置文件

const { injectBabelPlugin } = require('react-app-rewired');

module.exports = function override(config, env) {
    // do stuff with the webpack config...
    config = injectBabelPlugin(
        ['import', { libraryName: 'antd', libraryDirectory: 'es', style: 'css' }],
        config,
    );
    
    return config;
  };

然后又用到了antd-mobile的Picker组件,所以此时需要将antd-mobile也配置进去。
开始是做了个数组

config = injectBabelPlugin(['import', [
        {
            libraryName: "antd-mobile",
            style: true
        },
        {
            libraryName: 'antd',
            style: true
        }
    ]], config);

然后重新npm start,访问页面报错了

./src/index.js
Error: .plugins[0][1] must be an object, false, or undefined
    at Array.forEach (<anonymous>)
    at Array.forEach (<anonymous>)

最终还是官网权威。最新的版本不支持数组形式了。

官网说明

但是官网给的例子感觉还是不清晰,最后结合其他文章给搞定了
正确的confing-overrides.js

const { injectBabelPlugin } = require('react-app-rewired');

module.exports = function override(config, env) {
    // do stuff with the webpack config...
    config = injectBabelPlugin(
        ['import', { libraryName: 'antd', libraryDirectory: 'es', style: 'css' }, "ant"],
        config,
    );
    config = injectBabelPlugin(
        ['import', { libraryName: 'antd-mobile', libraryDirectory: 'es', style: 'css' }, "antd-mobile"],
        config,
    );
    return config;
  };

重点是为每个config加了个name,如上所示的两个import开头行末尾的"ant"和"antd-mobile”。否则会报如下错误

./src/index.js
Error: Duplicate plugin/preset detected.
If you'd like to use two separate instances of a plugin,
they need separate names, e.g.

  plugins: [
    ['some-plugin', {}],
    ['some-plugin', {}, 'some unique name'],
  ]
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容