简体   繁体   中英

Webpack import React component from directory

I have a problem. I made my project with create-react-app and I this is basically my structure:

src
├── app
│   ├── index.js
│   └── …
├── navigation
│   ├── index.js
│   └── …
└── …

My app/index.js

import App from 'app/App';

export default {
  App
};

My navigation/index.js:

import Navigation from 'navigation/Navigation';

export default {
  Navigation
};

The problem is that I can easily import from directory like:

import { App } from './app';
import { Navigation } from '.navigation';

The problem is that importing Navigation works as expected and importing App doesn't work. When I import App like above I get 'app' does not contain an export named 'App' and if I try importing it like this:

import App from './app';

I get an object like this {App: function(){}} and if I render it like <App.App /> it works as expected. Only difference is that App is class component and Navigation is function component.

If you have single import in your file you can use:

export default FileName

If you have multiple imports you can use:

export { FileName1, FileName2}

Incase you want to export certain file as default from multiple files exported you can use:

export {default as FileName1, FileName2}

The problem is that you're exporting via a weird object-like syntax:

export default {
  Navigation
}

You need:

export default Navigation

Edit: pasting my comment below here with better formatting

You can only have one default export (even that's optional), but there's no limit to the total number. You can have:

// exports.js
export const a = 1
export const b = 2
export function exportTest () {}
// then a default
export default a 

But - importing non-defaults happens only with the bracket syntax, let's say you want to import b which is a non-default export, you would need to use:

import { b } from 'exports' 
// or:
import { b as localName } from 'exports'

While you can import a default without the brackets and give it any name:

import whatever from 'exports'
console.log(whatever) // prints 1, as const a = 1 in exports.js

See 2ality.com/2014/09/es6-modules-final.html for more...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM