node.js - npm 本地路径 - 是否可以从子文件夹导入?

标签 node.js reactjs npm

鉴于以下利用 local paths 的文件夹结构:

dist
  components
    Button.js
  index.js
src
  components
    Button.js
  index.js
website
  pages
    components
      button.js
  package.json
  ...
package.json

src/components/Button.js

export const VARIANTS = ["primary", "secondary"];

function Button({ variant = "primary"}) {
  ...
}

Button.propTypes = {
  variant: PropTypes.oneOf(VARIANTS),
};

export default Button;

src/index.js

export { default as Button } from "./components/Button";

网站/package.json

{
  "dependencies": {
    "design-system": "file:..",
    ...
  }
  ...
}

package.json

{
  "name": "design-system",
  "main": "dist/index.js",
  "scripts": {
    "transpile": "rimraf dist && babel src -d dist",
    ...
  },
  ...
}

导入Button工作正常:

website/pages/components/button.js

import { Button } from "design-system";

但是,直接从子文件夹导入不起作用:

website/pages/components/button.js

import { VARIANTS } from "design-system/components/Button";

This dependency was not found: design-system/components/Button

我在这里缺少什么?

最佳答案

当您从 design-system 导入时,如下所示:

import { Button } from "design-system";

因为您的 package.json 中有一个 "main": "dist/index.js" 字段,所以它与:

import { Button } from "design-system/dist/index.js";

这有效,因为文件存在。

要从 dist 文件夹导入任何其他模块,您必须具体并从 design-system/dist 开始:

import { VARIANTS } from "design-system/dist/components/Button";

关于node.js - npm 本地路径 - 是否可以从子文件夹导入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57847710/

相关文章:

node.js - 平均堆栈 : How to handle internationalization in front end error messages?

node.js - 模块.exports : is not a constructor error

javascript - 如何显示来自旧组件的数据

javascript - 动态键类型与 typescript 中的其他键类型

reactjs - 使用 Link 导航时,具有 next-redux-wrapper 状态的 Next.js 被重置为初始值

javascript - 商店更新时我的组件不会重新渲染

javascript - 如何在 Laravel 中导入 Progressbar.js?

node.js - Webpack:如何加载原始 Node `.node` 文件

javascript - 将 owl carousel 包含到 npm 项目中。All ways

node.js - Winston 没有将日志写入文件