reactjs - 命名导出/导入与绝对路径导入
问题描述
我正在实现一个组件库(一个 npm 模块,我们称之为awesome-components
),它由按钮、输入、下拉列表等组成,最终用户可以将其安装在他们的 react 应用程序中并使用这些组件。我的困惑是为最终用户打包这个库的最佳方式是什么?我想到了两种方法,
- 使用
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";
- 通过没有
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 个。就可伸缩性和性能而言,最好的使用方法是什么?
非常感谢 :)
解决方案
您的第一种方法更可取,主要有四个原因。
- 在您的第二种方法中,路径可能会在某个时候发生变化,这将导致您的所有用户发生重大变化。
- 第二种方法中的子模块通常被认为是该包的外部消费者不应依赖的私有 API。
- 其他人都按照您在第一种方法中概述的方式进行操作。
- 当您使用来自外部包的子模块导入时,一些 linter ,如 TSLint 会抱怨。
推荐阅读
- python - Python 消息:进程以退出代码 0 完成
- javascript - CryptoJS 解码 PHP
- mysql - 使用滞后访问mysql中的前一行值
- c++ - C++ 复制/移动和析构函数调用
- javascript - 关闭前一个套接字实例 javascript
- go - 在go中输入字符串参数作为接口函数?
- python - MoviePy - 使用 VideoFileClip 将剪辑附加到列表时出错
- dataframe - 主成分分析 - 函数对象没有属性“loc”
- javascript - Vue.js Vuetify v-file-input with required rule 在选择文件之前显示所需的错误
- spring-boot - spring boot vaadin 14 build for production 失败