3

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?

1 Answer 1

7

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!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.