Skip to content

eschaefer/codemod-get-to-optional-member-expressions

Repository files navigation

codemod-get-to-optional-member-expressions

This repository contains a codemod script for use with JSCodeshift.

Overview

The codemod replaces calls to Lodash's get method with the native optional chaining proposal for ECMAScript. This is a novel new way to reliably access deeply nested object properties, and can be used now with @babel/plugin-proposal-optional-chaining. It is important to note that this will currently only work with Babel 7. If you are using Babel 6.x, then you will need to update your project to Babel 7 to use this codemod.

const foo = get(data, 'crate.box.present.wrapping.color');
const bar = get(data, 'crate.box.present.wrapping.color', 'green');

// 👇 Becomes 👇

const foo = data?.crate?.box?.present?.wrapping?.color;
const bar = data?.crate?.box?.present?.wrapping?.color || 'green';

Setup & Run

npm install -g jscodeshift
git clone https://github.com/eschaefer/codemod-get-to-optional-member-expressions.git
cd codemod-get-to-optional-member-expressions/
jscodeshift -t ./lodash-get-to-optional-member-expressions.js <file(s)>

Use the -d option for a dry-run and use -p to print the output for comparison.

Run tests for this codemod

npm run test

TODO

  • Add support for require;
  • Add support for string literal member expressions
  • Add support for array paths

About

Change Lodash `get` functions to ES7 optional member expressions

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published