Closed trivikr closed 2 years ago
The transformation with ImportDeclaration probably doesn't work with --parser=ts
as TypeScript transpiles the code to use require before transformation can process the file.
This happens because literal is of type StringLiteral
when parser=ts and is of type Literal
when parser=babel.
This can be fixed by removing type: "Literal"
from transformer:
// transform.js
module.exports = function (fileInfo, api) {
const j = api.jscodeshift;
const source = j(fileInfo.source);
source
.find(j.ImportDeclaration, {
source: { value: "react" },
})
.replaceWith((nodePath) => {
const { node } = nodePath;
node.specifiers = [j.importDefaultSpecifier(j.identifier("Vue"))];
node.source.value = "vue";
return node;
});
return source.toSource();
};
Tested fix in https://stackblitz.com/edit/node-tzzm8u?devtoolsheight=33&file=transform.js
Describe the bug
The transformation doesn't work on a TypeScript file when
--parser=ts
is passed.Steps to reproduce
Stackblitz: https://stackblitz.com/edit/node-dykwqt?devtoolsheight=33&file=transform.js Run
npx jscodeshift example.ts --parser=ts
in console.To reproduce in your workspace, add the following files:
transform.js
```js // transform.js module.exports = function (fileInfo, api) { const j = api.jscodeshift; const source = j(fileInfo.source); source .find(j.ImportDeclaration, { source: { type: "Literal", value: "react" }, }) .replaceWith((nodePath) => { const { node } = nodePath; node.specifiers = [j.importDefaultSpecifier(j.identifier("Vue"))]; node.source.value = "vue"; return node; }); return source.toSource(); }; ```example.ts
```ts // example.ts import React from "react"; ```Observed behavior
On running the command with
--parser=ts
the transformation doesn't happen:Expected behavior
The transformation to complete as follows:
With contents of
example.ts
changed to:Additional context
aws-sdk-js-codemod
in https://github.com/trivikr/aws-sdk-js-codemod/issues/84