Search code examples
javascriptecmascript-6webpackes6-module-loader

Index.js module imports with webpack


My code is organised as follows:

Folder hierarchy

where,

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
);

Why does Layout not get imported using this setup??

If i change the line to read,

import Layout from './Components/Layout';

it works fine, but otherwise Layout is always undefined! Even when if i try,

import Layout from './Components/index';

I am using webpack as my module bundler, and have achieved something similar before, I just don't see why/how this is different..


Solution

  • Why does Layout not get imported using this setup??

    Layout.js has a default export. However, export * from './Layout.js will only export the named exports (of which there are none). In other words, Components/Layout.js doesn't have any exports at all, so nothing can be imported.

    But even if it did have named exports, import Layout from './Components/index'; imports the default export, but Components/index.js doesn't have a default export.


    There are a couple of ways this could be solved. The one that makes the most sense is probably to export the default export of Layout.js as named export in Components/index.js. You will presumably have multiple files each exporting a component. I assume Components/index.js should export a map of all these components in which case you have to use named exports.

    The changes you have to make:

    // in Components/index.js
    export {default as Layout} from './Layout';
    
    
    // in ActionLog/index.js
    import {Layout} from './Components'; // use a named import