Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Module not found: Error: Can't resolve './components/PropTest1' - React JS

Tags:

reactjs

I have the following directory structure for my REACTJS app

/ReactJs
-dist
--app
-node_modules
-src
--app
--app/Hello.jsx
----components
----components/PropTest1.jsx
-src/main.html 
package.json 
webpack.config.js

My Hello.jsx code is:

import React, { Component } from 'react';
import ReactDOM, { render } from 'react-dom';

import PropTest1  from "./components/PropTest1"



var dest = document.querySelector('#container');

class Hello extends Component {
    render() {
        return (
        <div>
        <h1>Hello World</h1>
        <PropTest1 />
        </div>

        );

    }

}

render(<div><Hello /></div>, dest); 

and PropTest1.jsx code is

import React, { Component } from 'react';



class PropTest1 extends Component {
    render() {
        return (
            <div>
              <p>  My name is no one</p>
            </div>
        );
    }
}

export default PropTest1;

and my webpack.config.js is

var webpack = require('webpack');
var path = require('path')

module.exports = {
  mode: "development",
  entry: path.resolve(__dirname, 'src') + "/app/Hello.jsx",
  output: {
    path: path.resolve(__dirname, 'dist') + "/app",
    filename: 'bundle.js',
    publicPath: '/app/'
  },
  module: {
          rules: [{
            test: /\.jsx?/,
            include: path.resolve(__dirname,'src'),  
            loader:'babel-loader'
          }]
  },
  resolve: {
    extensions: ['*', '.js', '*.jsx']
}
};

When I am doing

npm run build

I am getting Module not found: Error: Can't resolve './components/PropTest1'

What looks wrong with the above project, please check.

EDIT: I have added the resolve configuration in my webpack.config.js

like image 406
RHM Avatar asked Dec 07 '22 14:12

RHM


2 Answers

The issue here is that you didn't specify the file extension (.jsx) while importing your component (import PropTest1 from "./components/PropTest1")

To solve this, you need to update Webpack config and add a resolve property, which will make Webpack look for files named (in your example) PropTest1.js, PropTest1.jsx until it finds the right one ...

module.exports = {
  mode: "development",
  entry: path.resolve(__dirname, 'src') + "/app/Hello.jsx",
  ...,
  resolve: {
      extensions: ['', '.js', '.jsx']
  }
};
like image 60
Hamza El Aoutar Avatar answered Dec 10 '22 05:12

Hamza El Aoutar


Currently,it is looking for components directory within app directory so, you need to use ..

import PropTest1  from "../components/PropTest1"
like image 39
CodeZombie Avatar answered Dec 10 '22 03:12

CodeZombie