Search code examples
javascriptreactjswebpackwebpack-2

import does not work in subfolder


When I use

import React from 'react';
import ReactDOM from 'react-dom';
require('./styles.css');
import App from './components/App';
import Test from './components/Test';

ReactDOM.render(
 <App />,
 document.getElementById('root')
);

webpack found the Test module however, in app component:

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

export class App extends React.Component {
  render() {
    return (
      <div className='container'>
        <Test />
     </div>
    )
  }
}

import Test does not work it says: ERROR in ./src/components/App.js Module not found: Error: Can't resolve './components/Test'

it works when I use require though

var Test = require('./Test');

Solution

  • You are importing from a wrong directory. From looking at your first code, you have both App and Test in the same components directory. The error comes because your import looks for a components folder inside the components folder. So if you want it to be imported into App, you should be specifying the relative path from your current folder. i.e) ./

    Try this in your App class or App.js file

    import Test from './Test';