Home > Software engineering >  What is the correct way of importing React Component in non-React build website?
What is the correct way of importing React Component in non-React build website?

Time:09-21

I built a site with Node, Express and want to add a page which is built with React and JSX.

I've installed Babel as npm package and added React as a script like this into index.html:

<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>

and Main module

<script src="./js/Main.js"></script>

My question is how to properly import a Child Component into a Parent Component.

Lets say I want to import './components/Message.js' into 'Main.js' like this

function Main() {
    return (
        <div>
            <h1>Hello World</h1>
            <Message />
        </div>
    )
}

const renderDiv = document.getElementById('chat-module')
ReactDOM.render(<Main />, renderDiv)

to do this I need to import Message.js into Main.js but import Message from 'components/Message' gives Uncaught SyntaxError: Cannot use import statement outside a module error.

The only solution I have found so far is to add Message.js as a script into index.html and call it from Main.js as window.Message

Is this the only available solution or is there more proper and efficient way to connect these components?

Note: As a reminder Im not using npx create-react-app. This is an existing app built with express.

CodePudding user response:

Did you try <script type="module" src="./js/Main.js">?

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules

  • Related