rollup包axios,不能用

Rollup package axios, can not be used

项目中使用axios,然后使用rollup打包

浏览器端正常。但是在nodejs端报错

错误信息:

node test\test.js
error
ReferenceError: XMLHttpRequest is not defined
    at dispatchXhrRequest (D:\Project\NodeJs\rollup-axios-error-demo\dist\demo.js:684:21)
    at new Promise (<anonymous>)
    at xhrAdapter (D:\Project\NodeJs\rollup-axios-error-demo\dist\demo.js:676:12)
    at dispatchRequest (D:\Project\NodeJs\rollup-axios-error-demo\dist\demo.js:1082:12)
    at process._tickCallback (internal/process/next_tick.js:68:7)
    at Function.Module.runMain (internal/modules/cjs/loader.js:745:11)
    at startup (internal/bootstrap/node.js:266:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:596:3)

我创建了一个可供您查看的演示:rollup-axios-error-demo

axios源码区分运行环境的代码为:

function getDefaultAdapter() {
  var adapter;
  if (typeof XMLHttpRequest !== 'undefined') {
    // For browsers use XHR adapter
    adapter = require('./adapters/xhr');
  } else if (typeof process !== 'undefined') {
    // For node use HTTP adapter
    adapter = require('./adapters/http');
  }
  return adapter;
}

但是打包后变成:

function getDefaultAdapter() {
  var adapter;
  if (typeof XMLHttpRequest !== 'undefined') {
    // For browsers use XHR adapter
    adapter = xhr;
  } else if (typeof process !== 'undefined') {
    // For node use HTTP adapter
    adapter = xhr;
  }
  return adapter;
}

导致在 nodejs 端实例化 XMLHttpRequest

万一有人偶然发现这个问题,我遇到了同样的问题,并通过在任何使用 axios 的文件中将 import axios from 'axios' 切换为 const axios = require("axios") 来解决它。