With the simplest React app, I can't import axios
without seeing this error in my console:
bundle.js:45314 Uncaught SyntaxError: Cannot use import statement outside a module
I created a base app with create-react-app
and installed a few packages:
npx create-react-app my-app
# Inside 'my-app/':
yarn install
yarn add axios
(I ran yarn install
again just in case.)
I added import axios from "axios"
to the default App.js
file as shown here:
import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
import axios from "axios"; // Here is the problem.
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
export default App;
With axios
imported, I get a blank screen and the error message I mentioned above.
This solution wanted me to add a line to index.html
, but it didn't do anything for me. Maybe I added it in the wrong place? Here is the line:
<script type="text/javascript" type="module" src="./index.js"></script>
This solution recommended the same line, or adding "type": "module"
to package.json
, but that also had no affect.
I was using React 18 when I encountered this problem, but I had a working React app using React 17. I switched "react"
and "react-dom"
to "^17.0.0"
in package.json
, but it didn't help, either.
Update 2022-11-18:
This is a problem specifically with Axios 1.x.x, and I can "solve" the problem by switching back to a 0.x.x version (0.27.2 is working for me).
Most developers seem to experience it with their Jest tests; see this discussion on GitHub and this other question. The latter was the most informative, but did not solve my problem.
I am not trying to run tests (yet). I'm just trying to use axios in my React app. I can revert to 0.x.x, or I can try using fetch
instead. But I would like to understand the source of the problem. I.e. I'd like to understand the implications of this statement:
The 1.x.x version of axios changed the module type from CommonJS to ECMAScript.
- (source)
Has anyone been able to make Axios 1.x.x work in a React app?