【发布时间】:2020-06-29 18:34:52
【问题描述】:
我有一个全局扩展,它定义了一个名为“is”的方法。我遇到的问题是 ESLink 将其标记为“no-undef”;尽管它在运行时可用。
禁用规则对我来说不是一个选项。我宁愿定义它,以便 ESLint 可以看到它。
我的项目正在使用 NodeJS、Vue、TypeScript、Babel 和 WebPack。没关系,但 typescript JavaScript 版本设置为 esnext。
以下是我希望您牢记的目标:
- 除此 ESLint 错误外,没有其他编译或运行时错误
- 如果我使用它在每个文件的顶部声明我的方法,一切正常
- 我希望有一种集中、简单的方式来为 ESLint 定义它
- 我没有使用类型定义文件 (AKA d.ts),因为您不能以这种方式定义它
// This is my 'is.ts' file; THIS IS NOT THE SAME AS A d.ts FILE
...
function is() { ... }
declare global {
function is(): boolean { ... }
}
// physically define on window giving my method global scope
const _LocalWindow: any = window;
_LocalWindow.is = _LocalWindow.is || is;
我的应用中的其他地方
declare function is(): boolean; // <== ONLY WAY TO PREVENT ESLINT ERROR 'no-undef'
if (is()) { // <== I DON'T WANT TO USE 'window.is'
...
}
作为参考,下面是我的 package.json 和 jsconfig.json 配置文件
// package.json
{
"name": "vuedatagriddemo",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"axios": "^0.19.2",
"core-js": "^3.6.4",
"vue": "^2.6.11",
"vue-class-component": "^7.2.2",
"vue-property-decorator": "^8.3.0",
"vue-router": "^3.1.5",
"vuetify": "^2.2.17",
"vuex": "^3.1.2"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^2.18.0",
"@typescript-eslint/parser": "^2.18.0",
"@vue/cli-plugin-babel": "~4.2.0",
"@vue/cli-plugin-eslint": "~4.2.0",
"@vue/cli-plugin-router": "~4.2.0",
"@vue/cli-plugin-typescript": "~4.2.0",
"@vue/cli-plugin-vuex": "~4.2.0",
"@vue/cli-service": "~4.2.0",
"@vue/eslint-config-airbnb": "^5.0.2",
"@vue/eslint-config-typescript": "^5.0.1",
"eslint": "^6.7.2",
"eslint-plugin-import": "^2.20.1",
"eslint-plugin-vue": "^6.1.2",
"sass": "^1.25.0",
"sass-loader": "^8.0.2",
"typescript": "~3.7.5",
"vue-template-compiler": "^2.6.11"
}
}
// tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"experimentalDecorators": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"types": [
"webpack-env"
],
"paths": {
"@/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}
【问题讨论】:
-
我也遇到了这个问题,几乎相同的设置。我的
global.d.ts文件正在运行,但只是从 eslint 收到no-undef错误。
标签: eslint webpack-dev-server typescript-typings typescript-eslint