使用组件路径从NPM包导入

xzlaal3s  于 2023-04-12  发布在  其他
关注(0)|答案(1)|浏览(160)

使用Material UI时,我可以通过两种方式导入模块:

  1. import { Box } from '@mui/material';
  2. // or
  3. import Box from '@mui/material/Box';

我查看了他们的源代码here,我注意到他们的项目结构如下

  1. /mui-material
  2. | package.json
  3. | tsconfig.json
  4. / src
  5. | <components>
  6. | index.js

(为了不丢失大图,我跳过了一些文件)
我一直在以类似的方式构建我的个人npm包。我成功地将其推送到我的NPM feed,但当我从另一个项目使用它时,我可以通过以下方式导入它:

  1. import { MyModule } from '@la27/utils';
  2. // or
  3. import MyModule from '@la27/utils/src/MyModule';

我怎样才能改变它,使我不需要使用“src”部分?

35g0bw71

35g0bw711#

您应该在utils目录中创建index.js文件,并导出index.js文件中的组件,如下所示:

  1. // this is the example for Material UI's Box component. Change it accordingly:
  2. export { default as Box } from './Box';
  3. export * from './Box';

在此处引用Material UI自己的index.js文件:https://github.com/mui/material-ui/blob/master/packages/mui-material/src/index.js
Upvote将不胜感激,如果这是有帮助的!

相关问题