Skip to content

Instantly share code, notes, and snippets.

@kawaz
Last active December 29, 2023 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kawaz/1b4e8ef716b57a7eb18c4efa5906a3a9 to your computer and use it in GitHub Desktop.
Save kawaz/1b4e8ef716b57a7eb18c4efa5906a3a9 to your computer and use it in GitHub Desktop.
jscodeshift の使い方メモ。

jscodeshift の使い方メモ。

Usage

↓こんな感じに実行すると、before/after のようにピンポイントでいい感じに修正されたコードが出てくる。みたいな感じに使える。

# -d を外すと元のファイルが修正される
bunx jscodeshift -t modify-video-provider.ts sample.js -d -p

before:

        this._singleSetup = requestVideoStream({
            width: {min: 480, ideal: 640},
            height: {min: 360, ideal: 480}
        })

after:

        this._singleSetup = requestVideoStream(Object.assign({
            width: {min: 480, ideal: 640},
            height: {min: 360, ideal: 480}
        }, this.videoDescripter))

型をつける

@types/jscodeshift を入れておくと型が付いて快適に書けるようになる。

bun add -d @types/jscodeshift jscodeshift

AST について

AST Explorer と一緒に使うととても捗る。 https://astexplorer.net

import { JSCodeshift, Collection, Transform, FileInfo, API } from "jscodeshift";
const modify_requestVideoStream_argument = (j: JSCodeshift, collection: Collection) => collection
.find(j.ClassDeclaration, { id: { name: "VideoProvider" }})
.find(j.MethodDefinition, { key: { name: "_setupVideo" } })
.find(j.CallExpression, {
callee: { name: "requestVideoStream" },
arguments: [{ type: "ObjectExpression" }]
})
.replaceWith(requestVideoStream_callExpression => {
const newArgs = [
j.callExpression(
j.memberExpression(j.identifier("Object"), j.identifier("assign")),
[
requestVideoStream_callExpression.node.arguments[0],
j.memberExpression(j.thisExpression(), j.identifier("videoDescripter"))
]
)
]
requestVideoStream_callExpression.node.arguments = newArgs
return requestVideoStream_callExpression.node
})
const transform: Transform = ({ path, source }: FileInfo, { jscodeshift: j }: API) => {
let rootCollection = j(source)
modify_requestVideoStream_argument(j, rootCollection)
return rootCollection.toSource()
};
export default transform;
import {requestVideoStream, requestDisableVideo} from './camera.js';
import log from '../log.js';
class VideoProvider {
// 略
_setupVideo () {
// We cache the result of this setup so that we can only ever have a single
// video/getUserMedia request happen at a time.
if (this._singleSetup) {
return this._singleSetup;
}
this._singleSetup = requestVideoStream({
width: {min: 480, ideal: 640},
height: {min: 360, ideal: 480}
})
.then(stream => {
this._video = document.createElement('video');
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment