React无法解析相对路径

时间:2020-02-13 13:55:13

标签: reactjs gatsby

在指定文件夹而不是确切的文件路径时,我遇到一个Module not found错误的问题。

例如:

src
 - containers
   - Navigation
     - Navigation.js
 - pages
   - index.js

Navigation.js

import React from "react"
import './Navigation.min.css'

class Navigation extends React.Component {
  render(){
    return(
      <div className="navigation">
      </div>
    )
  }
}

export default Navigation;
index.js

import React from "react"
import Navigation from '../containers/Navigation'

export default () => (
  <div>
    <Navigation />
  </div>
)

尝试导入导航引发Module not found: Error: Can't resolve '../containers/Navigation',但是当我指定import Navigation from '../containers/Navigation/Navigation.js时,它确实起作用。

没有显式文件名,我似乎无法使其正常工作。

1 个答案:

答案 0 :(得分:1)

您需要修复导入路径

// the correct import path depending on your hierarchy 
import Navigation from '../../containers/Navigation'

“ ../”用于文件夹树中的一个文件夹。

// will not work because your now in the Navigation folder
import "../container/Navigation "

import "../container/Navigation/Navigation" // will work becuase now you are pointing to a file, and you can omit the extenstion