【问题标题】:Is there a better way I can import/export a library of components?有没有更好的方法可以导入/导出组件库?
【发布时间】:2021-11-21 21:05:03
【问题描述】:

我有一个组件库,我使用index.ts 来导入/导出组件。在构建组件时,我必须添加更多的导入以及更多的导出。这项工作增长了O(n)

有没有办法可以导出所有导入的文件?这样我只需要导入组件,这会将工作减少一半。这些组件将被命名为导入,例如import { ComponentOne, ComponentTwo } from '@library'

index.ts

// Imports: Components
import ComponentOne from '../src/components/ComponentOne';
import ComponentTwo from '../src/components/ComponentTwo';
import ComponentThree from '../src/components/ComponentThree';
import ComponentFour from '../src/components/ComponentFour';

// Exports
export {
  ComponentOne,
  ComponentTwo,
  ComponentThree,
  ComponentFour,
}

【问题讨论】:

    标签: javascript node.js reactjs react-native


    【解决方案1】:

    如果您不想维护 index.js 文件,可以使用 babel-plugin-wildcard

    # install plugin
    npm i babel-plugin-wildcard --save-dev
    

    在 babel.config.js 中的插件部分添加通配符:

    module.exports = {
      presets: ['module:metro-react-native-babel-preset'],
      plugins: ['wildcard'], // <-- add this
    };
    
    

    用法:

    |- index.js
    |- dir
        |- a.js
        |- b.js
    

    index.js:

    import * as Items from './dir';
    
    console.log(Items.A);
    console.log(Items.B);
    

    查看插件 GitHub 页面 here 了解更多信息。

    【讨论】:

      【解决方案2】:

      您可以从您正在处理的同一个文件中export,例如,

      export default ComponentOne;
      

      无需像您一样为导出和导入创建另一个文件。

      【讨论】:

        【解决方案3】:

        您还可以查看 MDN Docs 的再导出/聚合

        语法会更简洁,即:

        export { ComponentOne } from '../src/components/ComponentOne';
        

        【讨论】:

        • 我将我的组件从默认导出切换到名称导出 + 这个。这通过使用export const componentOne 删除冗余在组件文件中为我节省了几行代码 + 通过在导入index.ts 时导出来修剪我的导入/导出的一半@
        【解决方案4】:

        您可以使用babel-plugin-module-resolver,它可以简化项目中的require/import 路径。例如,您可以编写 utils/my-utils,而不是使用像 ../../../../utils/my-utils 这样的复杂相对路径。它可以让您更快地工作,因为您无需计算在访问文件之前必须上多少级目录。

        // Use this:
        import MyUtilFn from 'utils/MyUtilFn';
        // Instead of that:
        import MyUtilFn from '../../../../utils/MyUtilFn';
        
        // And it also work with require calls
        // Use this:
        const MyUtilFn = require('utils/MyUtilFn');
        // Instead of that:
        const MyUtilFn = require('../../../../utils/MyUtilFn');
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-09-23
          • 2018-03-13
          • 1970-01-01
          • 2017-05-17
          • 2011-09-17
          • 1970-01-01
          • 2017-08-29
          • 1970-01-01
          相关资源
          最近更新 更多