https://github.com/eschaefer/codemod-get-to-optional-member-expressions
Change Lodash `get` functions to ES7 optional member expressions
https://github.com/eschaefer/codemod-get-to-optional-member-expressions
Last synced: 14 days ago
JSON representation
Change Lodash `get` functions to ES7 optional member expressions
- Host: GitHub
- URL: https://github.com/eschaefer/codemod-get-to-optional-member-expressions
- Owner: eschaefer
- Created: 2018-06-09T19:35:39.000Z (almost 7 years ago)
- Default Branch: master
- Last Pushed: 2018-06-10T15:09:38.000Z (almost 7 years ago)
- Last Synced: 2025-03-26T02:28:05.350Z (21 days ago)
- Language: JavaScript
- Homepage:
- Size: 39.1 KB
- Stars: 5
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
- awesome-codemods - codemod-get-to-optional-member-expression - Change Lodash `get` functions to ES7 optional member expressions. (ESNext)
README
## codemod-get-to-optional-member-expressions
This repository contains a codemod script for use with
[JSCodeshift](https://github.com/facebook/jscodeshift).### Overview
The codemod replaces calls to Lodash's [get](https://lodash.com/docs#get) method with the native [optional chaining proposal](https://claudepache.github.io/es-optional-chaining/) 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](https://new.babeljs.io/docs/en/next/babel-plugin-proposal-optional-chaining.html). 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.
```javascript
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
```sh
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
```Use the `-d` option for a dry-run and use `-p` to print the output for
comparison.Run tests for this codemod
```sh
npm run test
```### TODO
- Add support for `require`;
- Add support for string literal member expressions
- Add support for array paths