This repository contains a codemod script for use with JSCodeshift.
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';
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
- Add support for
require
; - Add support for string literal member expressions
- Add support for array paths