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

在Lit+Esbuild+TS的Modern Web环境中引入Axios遇转换错误

LitElement + ESBuild 集成 Axios 时出现 Node.js 模块解析错误

最小可复现示例

  • 可通过指定仓库复现问题
  • 执行 npm run start 或 npm run test 即可触发问题

问题详情

我在LitElement+TypeScript+ESBuild的项目中添加Axios依赖后,修改了MyElement.ts文件:

import axios from "axios";

export class MyElement extends LitElement {
  static styles = css`
    :host {
      display: block;
      padding: 25px;
      color: var(--my-element-text-color, #000);
    }
  `;

  @property({ type: String }) title = 'Hey there';

  @property({ type: Number }) counter = 5;

  __increment() {
    this.counter += 1;
    axios.get('https://example.com').then(
        res => {
          console.log(res)
        }
    )
  }
}

执行npm start或npm test后出现以下错误:

Error while transforming node_modules/axios/lib/platform/node/classes/URLSearchParams.js: Could not resolve import "url".

  1 | 'use strict';
  2 | 
> 3 | import url from 'url';
    |       ^
  4 | export default url.URLSearchParams;
  5 | 

我尝试通过npm i url安装依赖(个人认为这并非正确解决方案),之后又出现新错误:

Error while transforming node_modules/axios/lib/adapters/http.js: Could not resolve import "http".

   6 | import buildURL from './../helpers/buildURL.js';
   7 | import {getProxyForUrl} from 'proxy-from-env';
>  8 | import http from 'http';
     |       ^
   9 | import https from 'https';
  10 | import followRedirects from 'follow-redirects';
  11 | import zlib from 'zlib';

我猜测问题出在Axios错误加载了Node.js环境的适配器,而非浏览器适配版本,但不知道如何解决。

内容的提问来源于stack exchange,提问作者Wim De Troyer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 07:25:32