Home > OS >  TypeScript is compiling into this failing JS file when importing a module. Why?
TypeScript is compiling into this failing JS file when importing a module. Why?

Time:11-13

I have a pretty basic TS file that looks like this

import axios from 'axios';

const url = 'https://jsonplaceholder.typicode.com/todos/1';

axios.get(url).then(res => {
  console.log(res.data);
});

That compiles into this (added some linebreaks for clarity)

"use strict";

exports.__esModule = true;

var axios_1 = require("axios");
var url = 'https://jsonplaceholder.typicode.com/todos/1';

axios_1["default"].get(url).then(function (res) {
    console.log(res.data);
});

When I try running it with node I get this error

TypeError: Cannot read properties of undefined (reading 'get')
    at Object.<anonymous> (/Users/john/programation/javascript/typescript_2/fetchjson/index.js:5:20)

True enough when I console.log(axios_1) it doesn't have any "default" key.

I thought the TS compiler would handle this basic stuff. What can I do?

CodePudding user response:

Looks like you have an old CommonJs-module version of 'axios', which has no esModuleInterop flag

Update your axios and try again


Or you may import it like

import * as axios from 'axios'

(axios page says default export is the same as the whole module)

  • Related