【发布时间】:2021-12-31 20:48:18
【问题描述】:
我几乎尝试了每一个教程和方法来让 Jest 识别导入语句。但是,我在 2021 年找不到可行的解决方案。
我尝试过的事情:
这是我目前的布局。我也尝试了很多其他方法。
错误信息:
/Users/lukeanglin/Desktop/Convene/frontend/convene/node_modules/expo-secure-store/build/SecureStore.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { UnavailabilityError } from 'expo-modules-core';
^^^^^^
SyntaxError: Cannot use import statement outside a module
1 | import { LOGIN_URL } from '../config/globals';
2 | import { LOG } from '../config/logger-conf';
> 3 | import * as SecureStore from 'expo-secure-store';
| ^
4 | import axios from 'axios';
5 | export async function login(email, password) {
6 | // Returns true if login succeeds and false on fail (also logs error message)
^^^^^^
SyntaxError: Cannot use import statement outside a module
1 | import { LOGIN_URL } from '../config/globals';
2 | import { LOG } from '../config/logger-conf';
> 3 | import { SecureStore } from 'expo-secure-store';
| ^
babel.config.json
{
"presets": ["@babel/preset-env"]
}
package.json
// stuff here
"type": "module",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",
"eject": "expo eject",
"lint": "eslint .",
"lint:fix": "eslint --fix",
"format": "prettier --write './**/*.{js,jsx,ts,tsx,css,md,json}' --config ./.prettierrc",
"test": "jest"
},
"jest": {
"transform": {
"^.+\\.[t|j]sx?$": "babel-jest"
}
},
// stuff here
重现步骤:
- 创建一个展览项目
- 安装 Jest 和 babel,以及 expo-secure-store
- 尝试导入 SecureStore
- 正确的函数对尝试导入 SecureStore 的文件执行某些操作
另外,导致导入错误的文件的全部内容在这里:
login.js
import { LOGIN_URL } from '../config/globals';
import { LOG } from '../config/logger-conf';
import * as SecureStore from 'expo-secure-store';
import axios from 'axios';
export async function login(email, password) {
// Returns true if login succeeds and false on fail (also logs error message)
try {
const response = await axios.post(LOGIN_URL, {
username: email,
password: password
});
// Save the token
const token = response['data']['token']
await SecureStore.setItemAsync('token', token);
return true;
} catch (error) {
LOG.error(
'Error on GET request to login for authentication OR error on storing token with SecureStore: \n' +
error
);
return false;
}
}
并且测试测试函数login。
任何具有 Jest 和 Babel 工作配置以使 SecureStore 等 ES6 模块正常运行(以及导入语句、导出等)的人可以帮助我,我将不胜感激!
TLDR - 如何使用 Jest 修复 SyntaxError: Cannot use import statement outside a module?
【问题讨论】:
-
您不能像在 login.js 文件中那样使用 commonjs 导入。改成es6导入
-
@nlta 如果你看到我的 package.json 我其实已经有了这个
-
@DerEchteKroate 您能否通过将其更改为 es6 导入来指定您的意思?
-
@Luke Anglin 查看您的 login.js 文件。您显然正在使用 commonjs 方法在第 4 行导入 axios。改成es6导入
标签: javascript node.js reactjs jestjs