2016-10-19 112 views
0

我的代碼的組織結構如下:Index.js模塊導入用的WebPack

Folder hierarchy

其中,

資源/ ActionLog /組件/ Layout.js

import React from 'react'; 

export default class Layout extends React.Component { 
    render() { 
     return (
      <p>Test</p> 
     ); 
    } 
} 

資源/ ActionLog/Components/index.js

export * from './Layout'; 

資源/ ActionLog/index.js

import React from 'react'; 
import ReactDOM from 'react-dom'; 

import Layout from './Components'; // <--- ISSUE HERE. 

const app = document.getElementById('app'); 
ReactDOM.render(
    <Layout/>, 
    app 
); 

爲什麼Layout沒有得到使用此設置進口?

如果我改變讀取行,

import Layout from './Components/Layout';

它工作正常,但在其他方面Layout永遠是不確定的!即使如果我嘗試,

import Layout from './Components/index';

我使用的WebPack作爲我模塊捆綁,和之前已經取得了類似的事情,我只是不明白爲什麼/這怎麼是不同的..

回答

3

爲什麼佈局不能使用此設置導入?

Layout.js有一個默認出口。但是,export * from './Layout.js將僅導出名爲的導出(其中沒有)。換句話說,Components/Layout.js根本沒有任何出口,所以什麼都不能導入。

但即使它確實有一個名爲出口,import Layout from './Components/index';進口默認出口,但Components/index.js沒有一個默認的導出。


有幾種方法可以解決這個問題。最有意義的一個可能是導出缺省導出Layout.js作爲Components/index.js中的命名導出。你大概會有多個文件,每個文件導出一個組件。我假設Components/index.js應導出所有這些組件的地圖,在這種情況下,您必須使用命名導出。

的變化,你必須做:

// in Components/index.js 
export {default as Layout} from './Layout'; 


// in ActionLog/index.js 
import {Layout} from './Components'; // use a named import 
+0

你,善良的先生,是一大福音。爲此歡呼,我想我仍然需要刷新我的ES6。 –