Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve module not found error in webpack/reactjs app?

I have created a reactjs/webpack app with an component created in main.js:

import React from 'react';
import cube  from 'my-module';

class MainLayout extends React.Component {

    constructor(props) {
        super(props);
        console.log('testing=main constructor')

        console.log(cube(3));

    }


    render() {
        console.log('main render' )
        return (
            <div>hello</div>
        );
    }
}

export default MainLayout

I am trying to get my head around import and export in es6 and created a module in the same directory:

// module "my-module.js"
export default function cube(x) {
  return x * x * x;
}

However I am getting this error:

ERROR in ./app/components/layouts/main/main.js
Module not found: Error: Cannot resolve module 'my-module' in ...

How can I resolve this error?

like image 520
bier hier Avatar asked Nov 23 '25 21:11

bier hier


1 Answers

If you don't specify a path (starting with ./) before the name of your module, webpack (using regular nodejs module resolution) will look for my-module in the nearest node_modules folder.

So if the file that contains your MainLayout class is in the same folder as the my-module.js then your import statement would look like:

import cube from './my-module'

If it was one level above it would look like:

import cube from '../my-module'

Then one above that:

import cube from '../../my-module'

and so forth.

It's possible to configure webpack with aliases or have it know about specific files that act like top-level modules. Another technique which I've found very useful is to structure your app like:

node_modules/
src/
  node_modules/
    app.js
    my-module.js

webpack.config.js

That way you can always look for any of your own modules without specifying a path since node will first look in your src/node_modules folder, then if it can't find it there, will look in your top level node_modules folder where all your npm packages live. If you do this though, make sure not to put src/node_modules in .gitignore!

like image 128
azium Avatar answered Nov 25 '25 09:11

azium