【问题标题】:Typescript gives error for its own compilationTypescript 为自己的编译提供错误
【发布时间】:2021-05-17 14:30:40
【问题描述】:

我的代码:

addMouseOverListenerForNavItems() {
    this.navList.addEventListener('mouseover', this.mouseOverListener.bind(this));
}

mouseOverListener(e) {
    const closestNavItem: HTMLElement = e.target.closest(".js-mainbar__navitem");
    clearTimeout(this.closeTimer);
    this.openTimer = setTimeout(() => {
        this.openFlyout(closestNavItem);

    }, this.flyoutDelayMs);
}

打字稿编译代码:

Menu.prototype.mouseOverListener = function (e) {
    var _this = this;
    var closestNavItem = e.target.closest(".js-mainbar__navitem");
    clearTimeout(this.closeTimer);
    this.openTimer = setTimeout(function () {
        _this.openFlyout(closestNavItem);
    }, this.flyoutDelayMs);
};

错误:

60:13 错误 'this' 到局部变量 @typescript-eslint/no-this-alias 的意外别名

59 和 60.line =

Menu.prototype.mouseOverListener = function (e) {
    var _this = this;

我应该怎么做才能修复这个错误?我想我已经正确使用了箭头功能。

.eslintrc.js

module.exports =  {
parser:  '@typescript-eslint/parser',  // Specifies the ESLint parser
extends:  [
  'plugin:@typescript-eslint/recommended',  // Uses the recommended rules from the @typescript-eslint/eslint-plugin
],
parserOptions:  {
  ecmaVersion:  2018,  // Allows for the parsing of modern ECMAScript features
  sourceType:  'module',  // Allows for the use of imports
},
rules:  {
    "curly": 1,
    "@typescript-eslint/explicit-function-return-type": [0],
    "@typescript-eslint/no-explicit-any": [0],
    "ordered-imports": [0],
    "object-literal-sort-keys": [0],
    "max-len": [1, 120],
    "new-parens": 1,
    "no-bitwise": 1,
    "no-cond-assign": 1,
    "no-trailing-spaces": 0,
    "eol-last": 1,
    "func-style": ["error", "declaration", { "allowArrowFunctions": true }],
    "semi": 1,
    "no-var": 0
},
};

控制台错误

【问题讨论】:

  • 您是否以某种方式将以前生成的 javascript 文件传递​​到您的转译器/linter 中?检查应仅应用于打字稿文件,因此您所描述的内容很奇怪。当你看到这个错误时,你能解释一下吗?你运行了什么命令?
  • 我在运行“npm start”时在 chrome 控制台上看到它。在你的建议之后,我在 tsconfig.json 添加了排除参数:“exclude”:[“node_modules”,“build”,“dist”,“src/**/*.js”] 仍然没有工作。
  • 如您所见,错误来自 linter
  • 我已将这些 # Ignore built files ./build/* ./dist/* 添加到 .eslintignore。仍然给出这些错误。
  • 编译好的javascript文件命名为menu.ts正常吗? (我在上面添加了截图)

标签: typescript webpack bind ts-loader


【解决方案1】:

我已经通过添加解决了这个问题

enforce: "pre"

到 webpack。

为了安全起见,您可以使用 enforce: 'pre' 部分来检查源文件,而不是被其他加载器(如 babel-loader)修改:

来源:https://github.com/webpack-contrib/eslint-loader

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 1970-01-01
    • 2019-09-22
    • 2017-04-02
    • 2015-04-11
    相关资源
    最近更新 更多