【问题标题】:Named exports/ imports vs imports with absolute path命名导出/导入与绝对路径导入
【发布时间】:2023-04-03 15:05:01
【问题描述】:

我正在实现一个组件库(一个 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 };

json 包的main 将指向组件根目录中的index.js。 npm 包会将所有组件捆绑到一个文件中,并且将是 npm packed 和 npm publisheded,看起来有点像这样,

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

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

import { Button, Input } from "awesome-components";
  1. 如下组件中没有index.js
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 个。就可扩展性和性能而言,最好的使用方法是什么?

非常感谢:)

【问题讨论】:

    标签: reactjs npm node-modules packaging


    【解决方案1】:

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

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

    【讨论】:

    • 非常感谢您的回复:) ..在方法1中,由于所有内容都打包到一个文件中,一旦组件数量增加,它会不会出现性能问题?
    • @HasithaShan 应该不会对性能产生明显影响。见this answer
    • @parrker9 一旦完成,库将包含近 20 个组件
    • @cengels 非常感谢..会通过这个并回复你:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-27
    • 2020-06-26
    • 1970-01-01
    • 2010-11-21
    • 2012-08-27
    • 2022-10-24
    • 2017-05-08
    相关资源
    最近更新 更多