【问题标题】:VS Code imports using the require syntax in React test cases在 React 测试用例中使用 require 语法导入 VS Code
【发布时间】:2021-11-06 11:02:43
【问题描述】:

最近,当我从建议中进行自动导入时,我发现我在 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"
  ],
}

【问题讨论】:

    标签: javascript reactjs visual-studio-code react-testing-library


    【解决方案1】:

    从新功能CommonJS auto imports我们知道:

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

    对于jsconfig.json,您可以将compilerOptions.module 设置为es2015。这样 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 函数。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-06
      • 2017-12-18
      • 2022-07-05
      • 1970-01-01
      • 2021-05-05
      • 2016-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多