我正在使用 create-react-app 构建一个 React 应用程序。
运行 ESLint 时出现以下错误:
8:3 error 'document' is not defined no-undef.
我的应用程序运行没有错误,但我在 2 个文件中收到此 ESLint 错误。 请参阅这些
.jsx
文件之一和我的 ESLint 配置。
index.jsx:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root'),
);
eslintrc.js:
module.exports = {
"extends": "airbnb",
"plugins": [
"react",
"jsx-a11y",
"import"
],
"env": {
"jest": true
}
};
我该如何解决这个问题?目前我会简单地忽略这两个文件......但我宁愿找到一个长期的解决方案。
在 eslint.rc 文件中设置 env 属性,例如
{
"env": {
"browser": true,
"node": true
}
}
如果您有
.eslintrc.json
文件,请添加以下代码片段。
{
...otherSettings,
"env": {
"browser": true,
"node": true
}
}
如果您没有
.eslintrc.json
那么您可以在 package.json
文件中添加这些设置。
{
...otherSettings,
"eslintConfig": {
"globals": {
"window": true
}
}
}
在您的
package.json
中,将 jest 的测试环境指定为 "jsdom"
,如下所示:
"jest": {
"testEnvironment": "jsdom"
}
我遇到了同样的问题,它对我来说效果很好。
在 .eslintrc 文件中设置:
env: {
browser: true
}
因此 eslint 会识别这些与浏览器相关的全局变量