创建一个可以再次导入并立即导出组件的文件



不知道为什么不工作。我曾经有

// file 1
import Box from '@/components/Box'
import Popup from '@/components/Popup'
const MDXComponents = {
Box,
Popup
}
// using MDXComponents somewhere in file 1

现在我想外包MDXComponents对象,因为它变得太大了。所以我创建了一个新文件:

// file 2
import Box from '@/components/Box'
import Popup from '@/components/Popup'
export default {
Box,
Popup
}

然后回到文件1,我做:

// file 1
import * as MDXComponents from './file2'
// using MDXComponents somewhere in file 1

它不让我这样做,但我不知道为什么?

当你这样做的时候:

export default {
Box,
Popup
};

设置默认导出到一个有两个属性的新对象。您需要像这样导入:

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;

当你这样做的时候:

export {
Box,
Popup
};

创建两个命名的导出你可以这样导入:

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

对于这个用例,还有一个快捷方式:

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

相关内容

  • 没有找到相关文章

最新更新