未找到模块:无法解析' ./ components / player'在' ... / score-board-app / src / components'

时间:2018-03-19 15:28:58

标签: javascript reactjs create-react-app

我使用Create-React-App构建一个小型React应用程序。完整代码存储在github

我的文件结构:

src
  components
    Players.js
    Player.js
App.css
App.js
index.css
index.js
...

App.js:

import React from 'react';
import './App.css';
import PropTypes from 'prop-types';// used to fix the error: 'PropTypes' is not defined
import Header from './components/Header';
import Players from './components/Players';

const App = (props) => (
  <div className="scoreboard">
    <Header title={props.title} />
    <Players />
  </div>
  );

App.propTypes = {
  title: PropTypes.string.isRequired
};


export default App;

Player.js:

import React from 'react';

const Player = (props) => (
  <div className="player">
    <div className="player-name">
      Jim Hoskins
    </div>
    <div className="player-score">
      <div className="counter">
        <button className="counter-action decrement"> - </button>
        <div className="counter-score">31</div>
        <button className="counter-action increment"> + </button>
      </div>
    </div>
  </div>
);

export default Player;

Players.js:

import React from 'react';
import Player from './components/Player';

const Players = () => (
  <div className="players">
    <div className="player">
      <div className="player-name">
        Jim Hoskins
      </div>
      <div className="player-score">
        <div className="counter">
          <button className="counter-action decrement"> - </button>
          <div className="counter-score">31</div>
          <button className="counter-action increment"> + </button>
        </div>
      </div>
    </div>
    <div className="player">
      <div className="player-name">
        Juan Li
      </div>
      <div className="player-score">
        <div className="counter">
          <button className="counter-action decrement"> - </button>
          <div className="counter-score">30</div>
          <button className="counter-action increment"> + </button>
        </div>
      </div>
    </div>
  </div>
)

export default Players;

行[{1}}导致此错误: enter image description here 但是,如果我将此行放在import Player from './components/Player';文件的顶部,则它不会报告此类编译错误。我真的想知道我的代码确实存在什么问题?

2 个答案:

答案 0 :(得分:6)

您的文件路径错误。 PlayerPlayers位于同一文件夹中,因此您只需说import Player from './Player'

答案 1 :(得分:0)

  • 删除node_modules目录
  • 删除package-lock.json文件
  • 运行npm install
  • 运行npm start