oxc/no-this-in-exported-function

Disallow this in exported functions

After import { save } from "./store", a call to save() has no object in front of it, so this is undefined and this.items throws. With import * as store, store.save() sees the module's exports as this, but a bundler can turn that into a plain save() call, and then the same code only breaks in the bundle.

The rule checks export function, export default function, and functions listed in export { name }. An arrow function inside one of them uses the same this, so it's checked too. export const save = function () {} and export default save aren't checked.

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"oxc/no-this-in-exported-function" = "error" # or "warn"

Examples#

example.js1 problem
export function save(item) {
  this.items.push(item);
}
example.js1 problem
function save(item) {
  return () => this.items.push(item);
}

export { save };
example.jsNo problems
const items = [];

export function save(item) {
  items.push(item);
}

Pass the object as an argument if the function works on more than one:

example.jsNo problems
export function save(store, item) {
  store.items.push(item);
}

A regular function or a class inside the exported function has its own this:

example.jsNo problems
export function createStore() {
  return {
    items: [],
    save(item) {
      this.items.push(item);
    },
  };
}

When not to use it#

A function you export so it can be attached to an object or called with .call() uses this on purpose. The rule reports it even if it declares a TypeScript this parameter.