Export JS module without importing it first

问题: I have the following structure for my JS components: /components /Menu /Menu.js /Menu.test.js /index.js /MenuItem /MenuItem.js /MenuItem.test.js...

问题:

I have the following structure for my JS components:

/components
  /Menu
    /Menu.js
    /Menu.test.js
    /index.js
  /MenuItem
    /MenuItem.js
    /MenuItem.test.js
    /index.js

The idea being we can have a folder for each component that can contain a test (and possible other files) and then if we just want to import the component we can rely on the use of the index.js to handle the directory import without having to reference the class inside the folder direct.

So for example:

Menu.js

class Menu extends Component {
  // ... more code ..
}
export default Menu;

index.js

export default from './Menu';

And then it can be used like:

import Menu from './components/Menu';

However I found that this didn't work and it couldn't find the module...

So to fix this I had to import Menu into the index.js before export:

import Menu from './Menu';
export default Menu;

But having looked at how other projects have structured their code, I have seen that they are using the former without having to import again...

For example: https://github.com/IBM/carbon-components-react/blob/master/src/components/Breadcrumb/index.js

See how they have exported from the Breadcrumb without having to do the import first... how have they achieved this?


回答1:

If you check the provided example, you will see they use this babel plugin.

So you can add one to your babel plugin stack.

Alternatively, you can look into using just export {default} from "./destination"; form which works as is.

  • 发表于 2019-02-14 19:30
  • 阅读 ( 168 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除