Skip to content

linter: add a new rule that disallows using this in an exported function #15359

@sapphi-red

Description

@sapphi-red

Description

It would be nice to have a rule that disallows using this in an exported function.

In most bundlers, the value of this is not preserved for exported functions.

// imported.js
export function method() {
  // `this` is the module namespace object of `imported.js` here
  // but in most bundlers, `this` becomes `undefined`
  // (or even if it's a namespace object, some properties would be missing due to tree-shaking)
  console.log(this);
}

// main.js
import * as namespace from './imported.js';
namespace.method();

See esbuild's document for more details.

I didn't find any existing rule for this.

Examples

Examples of incorrect code for this rule:

export function foo() {
  console.log(this) // warn this
  this.something // warn this
  const self = this // warn this
}

Examples of correct code for this rule:

function foo() {
  console.log(this)
  this.something
}

export const bar = () => {
  console.log(this)
  this.something
}

Category

I guess this should be suspicious. It is fine to use this unless it's bundled, so this should not be correctness.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-linterArea - Lintergood first issueExperience Level - Good for newcomers

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions