admin管理员组

文章数量:1352882

I'm using React + TypeScript. The application I'm developing is based on the idea of different components: essentially, each one is a function that returns a custom <div> element, and the user can select the components he wants visualize. This selection happens in a list in the sidebar, and they get displayed in the main container (next to the sidebar) inside a flexbox.

Each component has its own file, with this basic structure:

(Example) ./components/FooComponent.tsx:

// import statements...

function FooComponent() {
    // code
    return (<div> {/* body of the component */} </div>);
}
export default FooComponent;

As of now, these files are stored in a directory called ./components/ inside the app. I no longer want that: as the project grows, more and more components will be added, and I want to import only the ones that the user wants to visualize. I decided to store them in a Component table on my database (and remove the files from the project). One of the table's attribute is the source code, i.e. the contents of the file.

What I'm having trouble with now is finding a way to import that code into my program and using it as if it were a file. How can I do such a thing?


What I've tried

I've tried using the import() function by passing it the contents of the file, but it didn't work. I've also tried writing the source code to a file and then importing it, but the fs module cannot be used in React.

本文标签: reactjsTypeScript How do I import string as moduleStack Overflow