我的代码组织如下:
在哪里,
资源/ActionLog/Components/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
?
如果我将行改为阅读,
从'./Components/Layout'导入布局;
它工作正常,但除此之外 Layout
总是未定义的!即使我尝试,
从'./Components/index'导入布局;
我正在使用 webpack 作为我的模块打包器,并且之前已经实现了类似的东西,我只是不明白为什么/有什么不同..
最佳答案
Why does Layout not get imported using this setup??
Layout.js
有一个默认 导出。但是,export * from './Layout.js
只会导出named 导出(其中没有)。换句话说,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
关于javascript - 使用 webpack 导入 Index.js 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40139864/