在 React 测试用例中使用 require 语法导入 VS Code

IT技术 javascript reactjs visual-studio-code react-testing-library
2022-07-30 01:00:47

最近,我发现当我从建议中自动导入时,我在 VS Code IDE 中的 react 项目在测试用例中使用了 require 语法。有人可以帮忙吗?

我正在使用 React 测试库,这就是它的样子。

const { render } = require("@testing-library/react");
const { default: Home } = require("../Home");

describe("Home", () => {
  it("should render Search page", () => {
    const { container } = render(<Home />);
  });
});

我有一个jsconfig.json文件如下

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": [
    "src"
  ],
}
1个回答

CommonJS 的新特性 auto imports中,我们知道:

如果 VS Code 检测到您正在使用 CommonJS 样式的 JavaScript module,自动导入现在将使用require而不是import.

您可以设置compilerOptions.modulees2015jsconfig.json 这样 js 文件将被检测为 ESM,自动导入将使用import而不是require.

jsconfig.json

{
  "compilerOptions": {
    "module": "es2015"
  },
}
// auto imports use `import` keyword.
import { render } from 'react-dom';

describe('Home', () => {
  it('should render Search page', () => {
    render
  });
});

有关 VS 代码何时使用的更多信息require,请参阅shouldUseRequire函数。

PS如果还是不行,添加此配置后尝试重新加载VS code的窗口。