I am working on a React application using TypeScript. I have the following simple post method:
import React, { useState } from 'react';
import axios from 'axios';
await axios.post('api/account/register', {
FirstName: formData.firstName,
LastName: formData.lastName,
Username: formData.email,
Password: formData.password,
IsLocked: true,
Role: 'Admin',
});
Below is the corresponding code from the js file:
const axios_1 = __importDefault(require("axios"));
const react_1 = __importStar(require("react"));
yield axios_1.default.post('api/account/register', {
FirstName: formData.firstName,
LastName: formData.lastName,
Username: formData.email,
Password: formData.password,
IsLocked: true,
Role: 'Admin',
});
It throws this exception: axios_1.default.post is not a function error. I have the latest version of axios installed.
Below is the ts.config
file:
{
"compileOnSave": true,
"compilerOptions": {
"module": "commonjs",
"jsx": "react",
"skipLibCheck": true,
"strict": true,
"moduleResolution": "node",
"target": "es6",
}
}
dependencies
inside package.json:
"dependencies": {
//other packages
"axios": "1.4.0"
},
Here you can find almost all project files:
https://github.com/erkaner/reactapp-peeraid
I have checked some other posts but could not find a solution to this problem. Any help?
2
Answers
I think the problem comes from typescript
config
file so all you need is to make sure that you enable feature calledesModuleInterop
This option helps with importing CommonJS modules, which includes libraries like
axios
for more info check this
part
from docsI just looked at your given repo and found out each
tsx?
file has a built version along side with the main file such as:which means the built version will get resolved as module instead of the
tsx?
file one during development.I guess you compile your code beforehand for some reason and definitely it’s not necessary at all.
As result of that, the thing you have to do is to get rid of those built files then everything should work fine. Here are some example of built files I mentioned which needs removing: