首页 > 解决方案 > 如何在索引文件中动态导入/导出组件?

问题描述

如何在 index.js 文件的文件夹中动态导入和导出所有模块?我正在使用 ReactJS 并希望在编译应用程序时(而不是在运行时)导入/导出。

// index.js
import ComponentA from './ComponentA';
import ComponentB from './ComponentB';
import ComponentC from './ComponentC';

export { ComponentA, ComponentB, ComponentC }

之后 - 但不起作用

// index.js
const fs = require('fs');

let components = {};

fs.readdirSync(__dirname)
    .filter((f) => f !== 'index.js')
    .forEach((file) => {

        if (file.toLowerCase().endsWith('.js')) {
            filePath = './'+file;
            fileName = file.split('.')[0];
            // Not sure how to write this part properly 
            components[fileName] = import(filePath);
            }
    });

export components; // SyntaxError: Unexpected token 'export'

标签: javascriptreactjsimportfrontendexport

解决方案


推荐阅读