与基于ES6的多个(React)Node.JS模块导入有问题
我一直在研究一个React项目,并且遇到一个问题,试图使用ES6导入几个导出的React节点模块。
这是我的代码:
我应该可以包含hello文件夹中的AddFriendInput和FriendList ,没有任何问题。 但是当webpack / babel编译时出现这个错误:
ERROR in ./src/common/containers/Menu/indexRender.js Module not found: Error: Cannot resolve 'file' or 'directory' ../../hello in /Users/markpaul/Documents/projects/patient-portal-app/src/common/containers/Menu @ ./src/common/containers/Menu/indexRender.js 122:13-35
我的AddFriendInput.js文件的内容如下所示:
import React, { Component, PropTypes } from 'react'; export default class AddFriendInput extends Component { constructor(props, context) { super(props, context); this.state = { name: this.props.name || '' }; } render() { return ( <div> </div> ); } }
我用babel的webpack来传输我的文件。 我的巴别configuration是:
{ "presets": ["react", "es2015", "stage-1"] }
我能做到的唯一方法就是做到这一点:
import AddFriendInput from '../../hello/AddFriendInput/AddFriendInput'; import FriendList from '../../hello/FriendList/FriendList';
但是,正如你所看到的,这看起来很可怕。
有人可以请帮忙。
提前致谢。
创buildhome / index.js
import AddFriendInput from './AddFriendInput' import FriendList from './FriedList' export { AddFriendInput, FriendList }
老解答:
将AddFriendInput.js
重命名为index.js
,之后您可以像这样导入:
import AddFriendInput from '../../hello/AddFriendInput'
ES6模块不会自动加载嵌套的目录/文件
通过目录名称导入( ../../hello
)意味着你有hello/index.js
更新
你可以像上面提到的@Sergey那样创buildhome / index.js,或者有一个名为auto-import的模块来监视你的目录并为你更新index.js。
我觉得你不了解这个共同点。
如果../../hello
是一个文件夹,nodejs将会findindex.js
文件。 所以你必须有一个文件../../hello/index.js
。
import AddFriendInput from '../../hello/AddFriendInput/AddFriendInput'; import FriendList from '../../hello/FriendList/FriendList'; module.exports = { AddFriendInput, FriendList };