Search code examples
javascriptreactjsrequirejsjsxbabeljs

In-browser javascript won't recognize "import" and JSX at the same time


I'm trying to create a simple React app that imports components from a components directory. Currently this is my folder structure:

main
|_components
|   |_FirstComponent.js
|_index.html

FirstComponent.js

export class FirstComponent extends React.Component{
    render(){
        return (
            <h1>Hello World</h1>
        )
    }
}

In index.html, I have scripts loading react, react-dom, and babel. Here is my JS code so far:

<script type="module">
    import FirstComponent from "./components/FirstComponent.js";
</script>

Which gives me the error: Uncaught SyntaxError: Unexpected token '<'

That's an error with JSX parsing, but when I switch the script type to text/babel:

<script type="text/babel">
    import FirstComponent from "./components/FirstComponent.js";
</script>

I get this error: Inline Babel script:2 Uncaught ReferenceError: require is not defined

In other words, if type is module, the browser can't read JSX, but if the type is babel, the browser doesn't recognize require, aka import.

How do I get the browser to properly load the component?


Solution

  • As a workaround, you can import your FirstComponent to your index.html page by simply doing this:

    <script type="text/babel" src="./components/FirstComponent.js"></script>
    

    And in FirstComponent.js, remove the import and export statements so that file only has the FirstComponent class/functional component. This will load the class as inline babel script and your component would be available to use. You can use ReactDOM.render() at the bottom of the index.html to render the component. This is an easy workaround.

    FirstComponent.js

    // No import statements
    class FirstComponent extends React.Component{
        render(){
            return (
                <h1>Hello World</h1>
            )
        }
    }
    // No export default statement