Immediate ES6 export (React, Webpack, Babel)

2019-07-06 21:24发布

问题:

At the root of a directory (e.g. components/, containers/), I have an index.jsx file which immediately exports out all components, so that I can import them like so:

    import {SampleOne, SampleTwo} from '../components'.

However, the root index.jsx file doesn't work with the following:

    import SampleOne from './SampleOne/SampleOne';
    import SampleTwo from './Sample/SampleTwo';

    export default {
      SampleOne,
      SampleTwo  
    };

So, I converted it to the following (which is basically the same):

    export {default as SampleOne} from './SampleOne/SampleOne';
    export {default as SampleTwo} from './SampleTwo/SampleTwo';

This works, however, I get this warning:

    Can't make class (SampleOne & SampleTwo) hot reloadable due to being read-only.
    To fix this you can try two solutions. First, you can exclude files or directories
    (for example, /node_modules/) using 'exclude' option in loader configuration.
    Second, if you are using Babel, you can enable loose mode for `es6.modules` using
    the 'loose' option. See: http://babeljs.io/docs/advanced/loose/
    and http://babeljs.io/docs/usage/options/

回答1:

After a lot of head-banging, we replaced

export {default as SampleOne} from './SampleOne/SampleOne';
export {default as SampleTwo} from './SampleTwo/SampleTwo';

with

import {default as SampleOne} from './SampleOne/SampleOne';
import {default as SampleTwo} from './SampleTwo/SampleTwo';

export {SampleOne, SampleTwo};

and that seems to be working for us.



回答2:

I had the same problem since I'm using a index.js in each modules to export all submodules like this:

export {default as SampleOne} from './SampleOne/SampleOne';
export {default as SampleTwo} from './SampleTwo/SampleTwo';

According to the discussion in the react-hot-loader repo, you can either ignore it(since it still got loaded) or don't re-export the modules.