Skip to content

Instantly share code, notes, and snippets.

@jamiebuilds
Last active June 16, 2021 20:53
Show Gist options
  • Save jamiebuilds/f4ff76397d31b69c484240379170af8c to your computer and use it in GitHub Desktop.
Save jamiebuilds/f4ff76397d31b69c484240379170af8c to your computer and use it in GitHub Desktop.

Object.hasOwn() codemod

We're looking for community feedback for the Object.hasOwn() TC39 proposal which is currently at Stage 3 and is being implemented in browsers.

If you successfully migrate your codebase to Object.hasOwn() please provide us with feedback even if its just a 👍

If you have any trouble with this codemod feel free to comment here.

Install the polyfill:

object.hasown

npm install object.hasown

Add it to your project:

import "object.hasown/auto"

// or

import hasOwn from "object.hasown"

if (!Object.hasOwn) {
	hasOwn.shim();
}

Run the codemod:

View Source@codemod/cli docs

npx \
  -p @codemod/cli \
  codemod \
  --remote-plugin https://astexplorer.net/\#/gist/d5ceeb062688edbd8bee8e98967a94be/84b76a4dfd3f6e89ba388aa70f25d351dd5af309 \
  src # replace with your source directory

Before:

import has from "has"
import lodash from "lodash"
import lodashDotHas from "lodash.has"
import lodashSlashHas from "lodash/has"
import * as lodashEs from "lodash-es"
import {has as lodashEsHas} from "lodash-es"
import lodashEsSlashHas from "lodash-es/has"

has(obj, "prop")
lodash.has(obj, "prop")
lodashDotHas(obj, "prop")
lodashSlashHas(obj, "prop")
lodashEs.has(obj, "prop")
lodashEsHas(obj, "prop")
lodashEsSlashHas(obj, "prop")

After:

Object.hasOwn(obj, "prop");
Object.hasOwn(obj, "prop");
Object.hasOwn(obj, "prop");
Object.hasOwn(obj, "prop");
Object.hasOwn(obj, "prop");
Object.hasOwn(obj, "prop");
Object.hasOwn(obj, "prop");

Caveats

  • This codemod does not support some lodash features like nested lodash.has(obj, "nested.properties")
  • There are minor differences between these libraries and Object.hasOwn() (very few people should be affected by this)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment