【问题标题】:Index.js module imports with webpack使用 webpack 导入 Index.js 模块
【发布时间】:2016-10-19 19:21:22
【问题描述】:

我的代码组织如下:

在哪里,

资源/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 无法使用此设置导入??

如果我将行改为读取,

import Layout from './Components/Layout';

它工作正常,但否则Layout 总是未定义!即使我尝试,

import Layout from './Components/index';

我正在使用 webpack 作为我的模块捆绑器,并且之前已经实现了类似的东西,我只是不明白为什么/如何不同..

【问题讨论】:

    标签: javascript ecmascript-6 webpack es6-module-loader


    【解决方案1】:

    为什么使用此设置无法导入布局??

    Layout.js 有一个 默认 导出。但是,export * from './Layout.js 只会导出 named 导出(其中没有)。换句话说,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
    

    【讨论】:

    • 您,好心的先生,真是天赐之物。为这个干杯,我想我仍然需要复习我的 ES6。
    猜你喜欢
    • 2018-03-15
    • 2016-09-06
    • 2017-04-24
    • 2018-01-27
    • 1970-01-01
    • 2020-02-20
    • 2018-07-26
    • 1970-01-01
    • 2020-05-05
    相关资源
    最近更新 更多