Can't resolve module (not found) in React.js

前端 未结 15 1226
太阳男子
太阳男子 2020-12-07 22:03

I can\'t believe that I\'m asking an obvious question, but I still get the error in console log.

Console says that it can\'t find the module in the directory, but I\

相关标签:
15条回答
  • 2020-12-07 22:29

    you should change import Header from './src/components/header/header' to

    import Header from '../src/components/header/header'

    0 讨论(0)
  • 2020-12-07 22:31

    in my case, The error message was

    Module not found: Error: Can't resolve '/components/body
    

    While everything was in the correct directory.

    I found that renaming body.jsx to body.js resolve the issue!

    So I added this code in webpack.config.js to resolve jsx as js

     module.exports = {
      //...
      resolve: {
        extensions: ['.js', '.jsx']
      }
    };
    

    And then build error gone!

    0 讨论(0)
  • 2020-12-07 22:31

    There is a better way you can handle the import of modules in your React App. Consider doing this:

    Add a jsconfig.json file to your base folder. That is the same folder containing your package.json. Next define your base URL imports in it:

    //jsconfig.json
    {
      "compilerOptions": {
        "baseUrl": "./src"
      }
    }
    

    Now rather than calling ../../ you can easily do this instead:

    import navBar from 'components/header/navBar'
    import 'css/header.css'
    

    Notice that 'components/' is different from '../components/'

    It's neater this way.

    But if you want to import files in the same directory you can do this also:

    import logo from './logo.svg'
    
    0 讨论(0)
提交回复
热议问题