SyntaxError: Cannot use import statement outside a module无论我尝试过什么,我都无法摆脱这个错误,这让我非常沮丧。有大佬解决了这个问题吗?我已经阅读了一百万个 stackoverflow 和 github 问题线程。没有明确的解决方案。
这是一个 React、Typescript、Webpack 项目。我正在尝试测试一个模块。但 Jest 不会改变以某种方式模块为普通的 javascript。
/Users/me/dev/Project/project/node_modules/variables/src/variables.js:12
import './main.js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
17 |
18 | */
> 19 | import { GlobalVars } from 'variables'
| ^
20 |
21 | export const Vars = new GlobalVars()
22 |
Run Code Online (Sandbox Code Playgroud)
使用env设置babel.config:env.test.preset: ['@babel/plugin-transform-modules-commonjs']
修改transformJest 配置中的设置'^.+\\.jsx?$': 'babel-jest', '^.+\\.tsx?$': …
我使用 typescript 用lit-html编写一个简单的演示:
import {html, TemplateResult} from 'lit-html';
export default function sayHello(name: string): TemplateResult {
return html`<h1>Hello ${name}</h1>`;
}
Run Code Online (Sandbox Code Playgroud)
并使用 jest 编写一些简单的测试:
import sayHello from "./sayHello";
import {render} from "lit-html";
beforeEach(() => {
render('', document.body);
})
describe('sayHello', () => {
it('says hello', () => {
render(sayHello('world'), document.body);
const component = document.querySelector('h1');
expect(component).toBeDefined();
})
})
Run Code Online (Sandbox Code Playgroud)
我的“jest.config.js”是:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
}
Run Code Online (Sandbox Code Playgroud)
但是当我用 运行测试时jest,我得到了这样的错误:
FAIL src/sayHello.test.ts
? Test suite failed to run
Jest encountered an …Run Code Online (Sandbox Code Playgroud)