首页 > 解决方案 > 命名导出/导入与绝对路径导入

问题描述

我正在实现一个组件库(一个 npm 模块,我们称之为awesome-components),它由按钮、输入、下拉列表等组成,最终用户可以将其安装在他们的 react 应用程序中并使用这些组件。我的困惑是为最终用户打包这个库的最佳方式是什么?我想到了两种方法,

  1. 使用index.js文件将要导入的所有组件导出为命名导入。文件夹结构如下,
src
  |-components
    |-Button
      |-index.jsx
    |-Input
      |-index.jsx
    |-index.js

index.js将执行如下,

import Button from "./Button";
import Input from "./Input";

export { Button, Input };

包 jsonmain将指向index.js组件根目录中的 。npm 包会将所有组件捆绑到一个文件中,并且会被npm pack编辑和npm published编辑,看起来有点像这样,

dist
  |-index.js
  |-index.js.map
  |-package.json

最终用户可以在他们的应用程序中导入这些组件,如下所示,

import { Button, Input } from "awesome-components";
  1. 通过没有index.js如下的 in 组件,
src
  |-components
    |-Button
      |-index.jsx
    |-Input
      |-index.jsx

并单独捆绑组件并运送给最终用户,保留看起来像这样的文件夹结构,

dist
  |-components
    |-Button
      |-index.js
      |-index.js.map
    |-Input
      |-index.js
      |-index.js.map

最终用户可以使用以下绝对路径使用这些组件,

import Button from "awesome-library/Button";
import Input from "awesoem-library/Input";

我担心的是,哪种方法会使最终用户受益?组件的数量甚至可以增加到 20 个。就可伸缩性和性能而言,最好的使用方法是什么?

非常感谢 :)

标签: reactjsnpmnode-modulespackaging

解决方案


您的第一种方法更可取,主要有四个原因。

  • 在您的第二种方法中,路径可能会在某个时候发生变化,这将导致您的所有用户发生重大变化。
  • 第二种方法中的子模块通常被认为是该包的外部消费者不应依赖的私有 API。
  • 其他人都按照您在第一种方法中概述的方式进行操作。
  • 当您使用来自外部包的子模块导入时,一些 linter ,如 TSLint 会抱怨。

推荐阅读