【问题标题】:npm local paths - is it possible to import from a subfolder?npm 本地路径 - 是否可以从子文件夹导入?
【发布时间】:2021-01-25 16:36:24
【问题描述】:

鉴于以下利用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 工作正常:

网站/页面/组件/button.js

import { Button } from "design-system";

但是,直接从子文件夹导入是行不通的:

网站/页面/组件/button.js

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

没有找到这个依赖:design-system/components/Button

我在这里错过了什么?

【问题讨论】:

  • 你有没有试过像'import { Button, tokens } from "design-system";' ?
  • 对不起,我弄错了。刚刚更新了问题。

标签: node.js reactjs npm


【解决方案1】:

当您像这样从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";

【讨论】:

    【解决方案2】:

    它应该可以正常工作 - 我的猜测是更新代码后您可能没有重新安装模块? 每次修改模块代码时都需要更新 node_module 副本,因为本地模块已复制到 node_modules 文件夹中。在你的项目根目录中尝试这样的事情:

    rm -rf node_modules/design-system && npm install
    

    然后检查它是否工作。

    【讨论】:

      猜你喜欢
      • 2013-07-12
      • 2017-11-04
      • 1970-01-01
      • 2016-05-14
      • 2018-03-08
      • 2017-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多