You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript导入axios编译为JS后运行报错,该如何解决?

问题描述

我有一个基础的TypeScript文件,代码如下:

import axios from 'axios';

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

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

编译后的JavaScript代码(格式化后):

"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);
});

使用Node运行该JS文件时出现如下错误:

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

打印axios_1后发现其并不包含default属性,请问该如何解决?

解决方案

1. 调整TypeScript编译配置

在项目的tsconfig.json中添加或修改以下配置项,让编译器自动处理ES模块与CommonJS模块的兼容性:

{
  "compilerOptions": {
    "module": "CommonJS",
    "moduleResolution": "Node",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true
  }
}
  • esModuleInterop: 开启后会为CommonJS模块生成默认导出的包装层,解决default属性不存在的问题。
  • allowSyntheticDefaultImports: 允许使用import xxx from 'module'的语法导入无默认导出的CommonJS模块。

2. 改用CommonJS风格导入

直接在TypeScript文件中使用CommonJS的导入方式,跳过ES模块的默认导出逻辑:

const axios = require('axios');

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

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

编译后会生成直接调用axios.get的代码,不会出现default属性的引用错误。

3. 使用命名导入语法

因为axios是CommonJS模块,其所有方法都挂载在模块对象上,可通过命名导入直接使用:

import * as axios from 'axios';

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

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

这种写法编译后会直接引用axios_1.get,避免对default属性的无效访问。

内容的提问来源于stack exchange,提问作者user1869935

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 09:55:20