Home > OS >  Creating a File that Imports & Immediately Exports Components Again
Creating a File that Imports & Immediately Exports Components Again

Time:06-17

Not sure why this isn't working. I used to have

// file 1
import Box from '@/components/Box'
import Popup from '@/components/Popup'

const MDXComponents = {
  Box,
  Popup
}

// using MDXComponents somewhere in file 1

Now I want to outsource the MDXComponents object, as it is getting too big. So I created a new file:

// file 2
import Box from '@/components/Box'
import Popup from '@/components/Popup'

export default {
  Box,
  Popup
}

And then back in file 1 I do:

// file 1
import * as MDXComponents from './file2'

// using MDXComponents somewhere in file 1

It doesn't let me do this, but I am not sure why?

CodePudding user response:

When you do this:

export default {
  Box,
  Popup
};

You set the default export to a new object that has 2 properties. You'd need to import like so:

import MDXComponents from './file2';
// And then destructure the object like any normal object.
// You can't do import {} in this case, you get the full object.
const { Box } = MDXComponents;

When you do this:

export {
  Box,
  Popup
};

You create two named exports that you can import like so:

// import all named exports
import * as MDXComponents from './file2';
// or just one individually
import { Box } from './file2';

For this use-case there's also a shortcut:

export { default as Box } from '@/components/Box';
export { default as Popup } from '@/components/Popup';

// If a module has named exports (not just a default export) 
// and you want to export them all:
export * from 'some-module';

// Or just some:
export { someOtherThing } from '@/components/Box';
export { default as Popup, someOtherThing } from '@/components/Popup';
  • Related