Index.js 使用 webpack 导入模块

Index.js module imports with webpack

我的代码组织如下:

其中,

Resources/ActionLog/Components/Layout.js

import React from 'react';

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

Resources/ActionLog/Components/index.js

export * from './Layout';

Resources/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 作为我的模块打包器,并且之前已经实现了类似的东西,我只是看不出 why/how 这是不同的..

Why does Layout not get imported using this setup??

Layout.js 有一个 default 导出。但是,export * from './Layout.js 只会导出 named 导出(其中有 none)。换句话说,Components/Layout.js 根本没有任何导出,因此无法导入任何内容。

但即使它确实有命名导出,import Layout from './Components/index'; 导入 default 导出,但 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