Axios“无法在模块外部使用 import 语句”

kni*_*irr 112 node.js vue.js axios

我有一个 Vue.js 应用程序,其中两个文件包含:

import axios from "axios"

这些文件位于应用程序内的 src/lib 中,并在第一行包含 import 语句。

无论 package.json 说什么,在 Github 上运行测试都会导致安装 Axios 1.0.0,现在涉及这些文件的任何测试都会失败并出现上述错误。

将语句更改为const axios = require("axios")也失败;node_modules/axios/index.js 在第 1 行包含一个 import 语句,并在那里抛出异常。

对于此类问题,我经常看到的一个建议是添加"type": "module"到 package.json (与 src/ 处于同一级别)。这会导致所有测试失败,并要求将 vue.config.js 重命名为 vue.config.cjs。这样做会让我: Error: You appear to be using a native ECMAScript module configuration file, which is only supported when running Babel asynchronously,我不明白。

谁能建议在这里做什么?

o0r*_*s0o 269

我能够通过强制 jest 导入 commonjs axios 构建来修复此错误,方法是添加

  "jest": {
    "moduleNameMapper": {
      "^axios$": "axios/dist/node/axios.cjs"
    }
  },
Run Code Online (Sandbox Code Playgroud)

给我的package.json。使用的其他解决方案transformIgnorePatterns对我不起作用。

  • 有人给这个人买啤酒,这是对我有用的唯一解决方案。StackOverflow 上的“transformIgnorePatterns”解决方案不起作用,我花了几个小时。这是唯一一个这样做的。谢谢@rcbevans (56认同)
  • 如果您使用react-scripts,则仅当您对package.json进行更改时才有效。我在jest.config.js中尝试过这个,但没有效果。 (9认同)
  • 谢谢,这也对我有用,但我必须将其添加到我的 jest.config.js 文件中。 (5认同)
  • 成功了!dist 路径可能因版本而异。对于我来说,它是“axios/dist/axios.js”,我必须添加一个全局窗口。但似乎已经奏效了! (4认同)
  • 请注意, moduleNameMapper 键是正则表达式,因此这个答案将影响任何包含“axios”的文件路径,即使它位于 `axios` 模块之外。您可以使用 `"moduleNameMapper": { "^axios$": "axios/dist/node/axios.cjs" }` 缩小范围 - 这更安全,可以避免无意的重新映射。 (4认同)
  • 非常感谢:我在创建的新测试套件中遇到了这个错误,并且将 axios 添加到“transformIgnorePatterns”在这种情况下毫无用处。您的解决方案解决了我的情况 (2认同)
  • @ToniMichelCaubet package.json 顶层的任何位置 ` { "name": "...", "version": "1.0.0", ... "jest": { "moduleNameMapper": { "axios": “axios/dist/node/axios.cjs”, } }, } ` (2认同)

Jun*_*nny 42

axios 1.xx 版本将模块类型从 CommonJS 更改为 ECMAScript。

axios index.js 文件的 0.xx 版本
module.exports = require('./lib/axios');
Run Code Online (Sandbox Code Playgroud)
axiox index.js 文件的 1.xx 版本
import axios from './lib/axios.js';
export default axios;
Run Code Online (Sandbox Code Playgroud)

基本上,jest 运行在 Node.js 环境上,因此它使用遵循 CommonJS 的模块。如果您想使用 1.xx 之前的 axios,您必须将 JavaScript 模块从 ECMAScript 类型转换为 CommonJS 类型。Jest/node_modules/基本上忽略目录进行转换。

所以你必须覆盖transformIgnorePatterns选项。有两种方法可以覆盖transformIgnorePatterns选项。

笑话配置.js

如果你的 vue 项目使用jest.config.jsfile,则添加此选项。

module.exports = {
  preset: "@vue/cli-plugin-unit-jest",
  transformIgnorePatterns: ["node_modules/(?!axios)"],
  ...other options
};
Run Code Online (Sandbox Code Playgroud)

包.json

如果你的 vue 项目使用package.jsonfile for jest,则添加此选项。

{
  ...other options
  "jest": {
    "preset": "@vue/cli-plugin-unit-jest",
    "transformIgnorePatterns": ["node_modules\/(?!axios)"]
  }
}
Run Code Online (Sandbox Code Playgroud)

这个正则表达式可以帮助您转换axios模块并忽略node_modules目录下的其他模块。


小智 29

将版本更新jest到 v29 在我的项目中解决了这个问题。可能是您的jest版本不兼容。

  • 答对了!这终于对我有用了。从 v27 升级到 v29 (6认同)
  • 谢谢![jest 28.0.0](https://github.com/facebook/jest/blob/main/CHANGELOG.md#2800):“添加对 package.json 导出的支持”解决了当我的代码为“type”时的语法错误: "commonjs"` 而 axios 1.0 的默认导出是 `"type": "module"`。 (2认同)

Mab*_*abd 20

快速解决

更新 npm run 测试脚本

 "test": "react-scripts test",
Run Code Online (Sandbox Code Playgroud)

 "test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!axios)/\"",
Run Code Online (Sandbox Code Playgroud)


小智 18

这对我有用:

在jest.config.js中添加moduleNameMapper

moduleNameMapper: {
    axios: 'axios/dist/node/axios.cjs',
},
Run Code Online (Sandbox Code Playgroud)


小智 7

我面临着同样的问题。首先使用的变体(在 package.json 文件内):

"jest": {
    "moduleNameMapper": {
      "axios": "axios/dist/node/axios.cjs"
    }
  },
Run Code Online (Sandbox Code Playgroud)

但为了模拟,我使用 axios-mock-adapter。我收到错误:

类型错误:mock.onGet 不是函数

我将代码更改为:

"jest": {
       "transformIgnorePatterns": [
          "/node_modules/(?!(axios)/)"
        ]
     }
Run Code Online (Sandbox Code Playgroud)

这个解决方案有效。版本:

  • “axios”:“^1.4.0”

  • “axios-模拟适配器”:“^1.21.5”

  • “@types/axios-mock-adapter”:“^1.10.0”


Cov*_*vik 2

我遇到类似的问题,但错误是由 引起的jest。\n所有尝试导入的测试都axios失败并抛出相同的异常:

\n
Test suite failed to run\n    Jest encountered an unexpected token\n    This usually means that you are trying to import a file which Jest cannot parse, e.g. it\'s not plain JavaScript.\n    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".\n    Here\'s what you can do:\n     \xe2\x80\xa2 If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.\n     \xe2\x80\xa2 To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.\n     \xe2\x80\xa2 If you need a custom transformation specify a "transform" option in your config.\n     \xe2\x80\xa2 If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.\n    You\'ll find more details and examples of these config options in the docs:\n    https://jestjs.io/docs/en/configuration.html\n    Details:\n    /monorepo/node_modules/axios/index.js:1\n    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import axios from \'./lib/axios.js\';\n                                                                                             ^^^^^^\n    SyntaxError: Cannot use import statement outside a module\n      1 | import { describe, expect, it } from \'@jest/globals\'\n    > 2 | import axios from \'axios\'\n
Run Code Online (Sandbox Code Playgroud)\n

解决方案很简单,应该用jest以下方法axios进行转换babel

\n
Test suite failed to run\n    Jest encountered an unexpected token\n    This usually means that you are trying to import a file which Jest cannot parse, e.g. it\'s not plain JavaScript.\n    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".\n    Here\'s what you can do:\n     \xe2\x80\xa2 If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.\n     \xe2\x80\xa2 To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.\n     \xe2\x80\xa2 If you need a custom transformation specify a "transform" option in your config.\n     \xe2\x80\xa2 If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.\n    You\'ll find more details and examples of these config options in the docs:\n    https://jestjs.io/docs/en/configuration.html\n    Details:\n    /monorepo/node_modules/axios/index.js:1\n    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import axios from \'./lib/axios.js\';\n                                                                                             ^^^^^^\n    SyntaxError: Cannot use import statement outside a module\n      1 | import { describe, expect, it } from \'@jest/globals\'\n    > 2 | import axios from \'axios\'\n
Run Code Online (Sandbox Code Playgroud)\n

注意:我正在使用 Quasar Vue,这是他们的实现。

\n