ES6模块的导入未定义。

11

我正在尝试解决我在使用ES6模块导入时遇到的问题。

以下是我尝试实现的简化版本。我的实际文件结构更加复杂,并且有嵌套的文件夹。

我有两个ReactJS组件:

/buttons
  /MyComponent1.js
  /index.js
/texts
  /MyComponent2.js
  /index.js

/index.js

我的文件看起来像这样:

我从根目录下的 index.js 文件中导入了 MyComponent2 组件,该文件是我的包的入口点。

MyComponent1.js

import MyComponent2 from '../../';

export default () => (
  <div><MyComponent2 /></div>
);

MyComponent2.js

export default () => (
  <div>Hello world</div>
);

我的 buttons/index.jstexts/index.js 文件导出了它们各自文件夹中的所有组件:

buttons/index.js

export { default as MyComponent1 } from './MyComponent1'; 

texts/index.js

export { default as MyComponent2 } from './MyComponent2';

我的根目录 index.js 导出所有的文件夹以使它们公开可用。这是我的入口点:

export * from './buttons';
export * from './texts';
所以当我从根目录的index.js文件中导入MyComponent2MyComponent1中时,它是undefined。当我从./MyComponent2.js中导入时,它是定义的。当我在另一个项目中导入整个包并从根目录的index.js文件中导入MyComponent2时,它是已定义的。 这让我很难理解,我不知道为什么不能从根目录的index.js文件中导入MyComponent2。 我需要这样做,因为我有一组嵌套在不同文件夹中的一百个组件,并且我想使它们都可以从此入口点文件中使用。 有人能告诉我发生了什么事情,以及如何使这成为可能吗? 谢谢

1
尝试简单导出:export default MyComponent1导入方式:import MyComponent1 from './index' - Artem Kolodko
我发现先将导入变量,然后单独导出的方式行得通。这种方式不行。 - Sinan Guclu
3个回答

9

好的,我花了一些时间才弄清楚发生了什么。请查看我设置的沙箱 - https://codesandbox.io/s/nk0qmo096j

我尝试保持文件夹/模块结构与您描述的相似。在继续阅读之前,请查看文件夹/模块的结构。

当您在沙箱中运行代码时,请查看控制台。您会看到类似于这样的内容-

enter image description here

让我试着解释一下为什么您正在尝试的事情不起作用:

  1. buttons / MyComponent是第一个要 "导出" 的文件(因为它在依赖链的底部; Project/index -> components/index -> buttons/index -> buttons/MyComponent)

请注意,components / index 还没有被导出,因此它将返回 undefined

  1. 然后导出 buttons/index,其次是 texts/index

  2. 然后渲染 buttons/MyComponent; 在它被呈现之前,我手动requirecomponents/index,现在已经定义,因此返回一些定义好的值

实质上,当您的 MyComponent1 尝试通过 index 文件导入 MyComponent2 时,index 文件尚未被导出,因此返回 undefined。为了解决这个问题,您必须从 MyComponent1 的渲染方法中要求 MyComponent2


1
感谢您提供这么详细的解释,真的很有帮助!虽然从渲染方法中导入看起来有点丑哈哈!我也愿意尝试其他的替代方案。 - alexmngn

2

您可以从各自的组件文件中导入所有组件,然后将它们分配给根组件中的变量,最后将它们全部导出为对象。

import MyComponent1 from './buttons/index'

import MyComponent2 from './texts/index'

export {MyComponent1, MyComponent2}

要在另一个文件或项目中导入这些组件,您可以使用对象解构仅导入其中一个。

import {MyComponent1} from 'index.js'

import {MyComponent2} from 'index.js'


-1
在我的情况下,我有一个旧的js文件,IDE导入了它而不是更新的ts文件。所以如果你的模块文件是module.js,请确保在同一目录下没有编译过的旧module.js文件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接