Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React import leads to Failed to resolve module specifier "react"

Tags:

reactjs

Call me stupid (and I will not take it personally), but I have not used REACT for over 3 years, and my brain cells must have died.

I am getting the error:

localhost/:1 Uncaught TypeError: Failed to resolve module specifier "react". Relative references must start with either "/", "./", or "../".

I am sure it has to do with how I am using the import in Chrome.

index.html

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <script src="../node_modules/react/umd/react.development.js"></script>
    <script src="../node_modules/react-dom/umd/react-dom.development.js"></script>
    <title>React App</title>
</head>

<body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <script type="module" src="Main.js"></script>
</body>

</html>

Main.jsx

import React from 'react'
import ReactDOM from 'react-dom'
import App from 'App'


ReactDOM.render(
    <App />, 
    document.getElementById("root")
);

Main.js

(after babel cli, with react preset)

import React from 'react';
import ReactDOM from 'react-dom';
import App from 'App';
ReactDOM.render(React.createElement(App, null), document.getElementById("root"));

App.jsx (located in same folder as Main.jsx (and babel creates App.js in same folder as Main.js)

import React, { Component } from 'react'

class App extends Component {
    render() {
        return (
            <div className="App">
                <h1>Hello World</h1>
            </div>
        );
    }
}

export default App;
like image 608
Dr.YSG Avatar asked Apr 19 '26 20:04

Dr.YSG


2 Answers

As you're not using a module bundler like Webpack, you can ditch the react import statements (it should already be globally exposed by the tag-based imports you have above), convert your App import to either absolute ('/'), or relative paths ('./','../') and include the file extension. To support older browsers incompatible with ES6 modules, import it instead with a script tag, or move the whole code into a single file.

like image 70
Drazen Bjelovuk Avatar answered Apr 23 '26 00:04

Drazen Bjelovuk


When you load the React script using a tag as in your example then the React and ReactDOM objects are already available to you.

In order to use Reacts components and functions you just use them straight away without any import calls. All you need to do is prepend your use with "React." i.e.

React.Component
React.useState 

and so on.

like image 38
J. Wrong Avatar answered Apr 22 '26 23:04

J. Wrong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!