newbreedofgeek
newbreedofgeek

Reputation: 3616

Having issues with ES6 based multiple (React) Node.JS Module imports

I've been working on a React project and I'm having an issue trying to use ES6 to import several exported React node modules.

This is my code:

enter image description here

I should be able to include the AddFriendInput and FriendList from the hello folder without any issue. But I get this error when webpack/babel compiles:

ERROR in ./src/common/containers/Menu/indexRender.js
Module not found: Error: Cannot resolve 'file' or 'directory' ../../hello in /Users/markpaul/Documents/projects/patient-portal-app/src/common/containers/Menu
 @ ./src/common/containers/Menu/indexRender.js 122:13-35

The content of my AddFriendInput.js file is like so:

import React, { Component, PropTypes } from 'react';

export default class AddFriendInput extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      name: this.props.name || ''
    };

  }
  render() {
    return (
      <div>

      </div>
    );
  }
}

I use webpack with babel to transpile my files. My Babel config is:

{
  "presets": ["react", "es2015", "stage-1"]
}

The only way I can get it to work is to do this:

import AddFriendInput from '../../hello/AddFriendInput/AddFriendInput';
import FriendList from '../../hello/FriendList/FriendList';

But as you can see, this looks horrible.

Can someone please help.

Thanks in advance.

Upvotes: 1

Views: 976

Answers (3)

Stephen Kingsley
Stephen Kingsley

Reputation: 559

I think you are not understand the commonJS.

if the ../../hello is a folder, nodejs will find index.js file. so you must be have a file ../../hello/index.js.

import AddFriendInput from '../../hello/AddFriendInput/AddFriendInput';
import FriendList from '../../hello/FriendList/FriendList';

module.exports = {
   AddFriendInput,
   FriendList
};

Upvotes: 0

Serhii Baraniuk
Serhii Baraniuk

Reputation: 3375

Create home/index.js

import AddFriendInput from './AddFriendInput'
import FriendList from './FriedList'

export { AddFriendInput, FriendList }

OLD ANSWER:

Rename AddFriendInput.js to index.js and after that you can import like this:

import AddFriendInput from '../../hello/AddFriendInput'

Upvotes: 2

aifarfa
aifarfa

Reputation: 3939

ES6 module doesn't automatically load nested directories/files

import by directory name (../../hello) implies that you have hello/index.js

updates

you could just create home/index.js as @Sergey mentioned or there is a module named auto-import that watch your directory and update index.js for you.

Upvotes: 1

Related Questions