gregjacobs / js-to-ts-converter Goto Github PK
View Code? Open in Web Editor NEWSmall utility to fix common js->ts issues in order to assist in migrating a codebase
License: MIT License
Small utility to fix common js->ts issues in order to assist in migrating a codebase
License: MIT License
I'm trying to convert my src set but the tool couldn't handle it,
Content of file stay without any change. No error.
info: Adding property declarations to JS Classes...
verbose: Parsing JS classes in the codebase...
verbose: Updating class 'OuiTable' in 'D:/dis/ui/src/main/webapp/src/js/app/modules/common/table/ouiTable.js'
verbose: Adding property declarations for properties: 'state', 'setState', 'props', 'lastQuery', 'pageSize', 'currentPage', 'sorting', 'searchStr', 'rows', 'prepareData', 'selection', 'intl', 'id', 'sort', 'pagination', 'rowActions', 'search', 'tableActions'
verbose: Updating class 'Pagination' in 'D:/dis/ui/src/main/webapp/src/js/app/modules/common/table/pagination.js'
verbose: Adding property declarations for properties: 'props', 'count', 'onChangePage', 'page', 'rowsPerPage', 'ActionsComponent', 'backIconButtonProps', 'classes', 'Component', 'labelDisplayedRows', 'labelRowsPerPage', 'nextIconButtonProps', 'onChangeRowsPerPage', 'rowsPerPageOptions', 'SelectProps'
verbose: Updating class 'paginationActions' in 'D:/dis/ui/src/main/webapp/src/js/app/modules/common/table/paginationActions.js'
verbose: Adding property declarations for properties: 'props', 'classes', 'count', 'page', 'rowsPerPage', 'theme'
verbose: Updating class 'Table' in 'D:/dis/ui/src/main/webapp/src/js/app/modules/common/table/table.js'
verbose: Adding property declarations for properties: 'state', 'columns', 'props', 'setState', 'lastQuery', 'pageSize', 'currentPage', 'sorting', 'intl'
verbose: Updating class 'TableHeader' in 'D:/dis/ui/src/main/webapp/src/js/app/modules/common/table/tableHeader.js'
verbose: Adding property declarations for properties: 'props'
info: Renaming .js files to .ts
C:\Users\vijthang.ORADEV\AppData\Roaming\npm\node_modules\js-to-ts-converter\node_modules\ts-simple-ast\dist\manipulation\nodeHandlers\StraightReplacementNodeHandler.js:34
finally { if (e_1) throw e_1.error; }
^
Error: Error replacing tree: Should not have new children left over.
at StraightReplacementNodeHandler.handleNode (C:\Users\vijthang.ORADEV\AppData\Roaming\npm\node_modules\js-to-ts-converter\node_modules\ts-simple-ast\dist\manipulation\nodeHandlers\StraightReplacementNodeHandler.js:38:19)
at NodeHandlerHelper.handleForValues (C:\Users\vijthang.ORADEV\AppData\Roaming\npm\node_modules\js-to-ts-converter\node_modules\ts-simple-ast\dist\manipulation\nodeHandlers\NodeHandlerHelper.js:10:21)
at StraightReplacementNodeHandler.handleNode (C:\Users\vijthang.ORADEV\AppData\Roaming\npm\node_modules\js-to-ts-converter\node_modules\ts-simple-ast\dist\manipulation\nodeHandlers\StraightReplacementNodeHandler.js:26:29)
at NodeHandlerHelper.handleForValues (C:\Users\vijthang.ORADEV\AppData\Roaming\npm\node_modules\js-to-ts-converter\node_modules\ts-simple-ast\dist\manipulation\nodeHandlers\NodeHandlerHelper.js:10:21)
at StraightReplacementNodeHandler.handleNode (C:\Users\vijthang.ORADEV\AppData\Roaming\npm\node_modules\js-to-ts-converter\node_modules\ts-simple-ast\dist\manipulation\nodeHandlers\StraightReplacementNodeHandler.js:26:29)
at NodeHandlerHelper.handleForValues (C:\Users\vijthang.ORADEV\AppData\Roaming\npm\node_modules\js-to-ts-converter\node_modules\ts-simple-ast\dist\manipulation\nodeHandlers\NodeHandlerHelper.js:10:21)
at StraightReplacementNodeHandler.handleNode (C:\Users\vijthang.ORADEV\AppData\Roaming\npm\node_modules\js-to-ts-converter\node_modules\ts-simple-ast\dist\manipulation\nodeHandlers\StraightReplacementNodeHandler.js:26:29)
at NodeHandlerHelper.handleForValues (C:\Users\vijthang.ORADEV\AppData\Roaming\npm\node_modules\js-to-ts-converter\node_modules\ts-simple-ast\dist\manipulation\nodeHandlers\NodeHandlerHelper.js:10:21)
at StraightReplacementNodeHandler.handleNode (C:\Users\vijthang.ORADEV\AppData\Roaming\npm\node_modules\js-to-ts-converter\node_modules\ts-simple-ast\dist\manipulation\nodeHandlers\StraightReplacementNodeHandler.js:26:29)
at NodeHandlerHelper.handleForValues (C:\Users\vijthang.ORADEV\AppData\Roaming\npm\node_modules\js-to-ts-
converter\node_modules\ts-simple-ast\dist\manipulation\nodeHandlers\NodeHandlerHelper.js:10:21)
Sample file
tableHeader.zip
No mater what I do - always getting same error
Stack: Error: Error replacing tree: The children of the old and new trees were expected to have the same count (12:13).
p.s. my code has copyright comment on top of each file
/home/douglas/.nvm/versions/node/v12.11.1/lib/node_modules/js-to-ts-converter/node_modules/ts-morph/dist/manipulation/helpers/getRangeWithoutCommentsFromArray.js:31
throw new errors.NotImplementedError(Unexpected! Inserted ${length} child/children, but ${children.length} were inserted.
);
All errors seem to print like this ie without doing the string interpolation being performed.
Also it fails on some simple files such as a dir containing this file (the file it fails on)
export class Base extends Error {
constructor(message = '') {
super(message)
this.name = this.constructor.name
Error.captureStackTrace && Error.captureStackTrace(this, this.constructor)
}
}
BTW It would be far better if it had a flag to convert all functions to typescript funcs with "any" types to reduce manual labor during migration or better even be able to be used in conjunction with a typescript declaration file so we could build a typescript code base automatically taking types from that (many projects have one written by hand).
I simply used js-to-ts-converter src
and it created a ton of ts files but none of them had import
statements in them.
The tool crashes on js files that contains self closing JSX components such as <div/>
Crash log:
Error: Error replacing tree: The children of the old and new trees were expected to have the same count (7:8).
-- Details --
Path: /Users/vincent/Code/sterblue/packages/apps/cloud/src/containers/__stories__/index.js
Text: "import React from \"react\";\nimport { storiesOf } from \"@storybook/react\";\n//import Mission from \"../Mission\";\n\nstoriesOf(\"Containers\", module).add(\"Expert\", () => <Expert />);\nconst match = {\n params: {\n id: \"mockId\"\n }\n};\nstoriesOf(\"Containers\", module).add(\"Mission DontTest\", () => (\n <Mission match={match} />\n));\n"
Stack: Error: Error replacing tree: The children of the old and new trees were expected to have the same count (7:8).
at StraightReplacementNodeHandler.handleChildren (/Users/vincent/.config/yarn/global/node_modules/ts-morph/dist/manipulation/nodeHandlers/StraightReplacementNodeHandler.js:26:19)
at StraightReplacementNodeHandler.handleNode (/Users/vincent/.config/yarn/global/node_modules/ts-morph/dist/manipulation/nodeHandlers/StraightReplacementNodeHandler.js:20:18)
at Object.doManipulation (/Users/vincent/.config/yarn/global/node_modules/ts-morph/dist/manipulation/manipulations/doManipulation.js:9:21)
at Object.replaceSourceFileForFilePathMove (/Users/vincent/.config/yarn/global/node_modules/ts-morph/dist/manipulation/manipulations/replaction.js:64:22)
at SourceFile._moveInternal (/Users/vincent/.config/yarn/global/node_modules/ts-morph/dist/compiler/ast/module/SourceFile.js:273:24)
at SourceFile.move (/Users/vincent/.config/yarn/global/node_modules/ts-morph/dist/compiler/ast/module/SourceFile.js:246:19)
at tsAstProject.getSourceFiles.forEach.sourceFile (/Users/vincent/.config/yarn/global/node_modules/js-to-ts-converter/dist/converter/convert.js:38:24)
at Array.forEach (<anonymous>)
at Object.convert (/Users/vincent/.config/yarn/global/node_modules/js-to-ts-converter/dist/converter/convert.js:29:35)
at doConvert (/Users/vincent/.config/yarn/global/node_modules/js-to-ts-converter/dist/js-to-ts-converter.js:62:22)
at Object.doManipulation (/Users/vincent/.config/yarn/global/node_modules/ts-morph/dist/manipulation/manipulations/doManipulation.js:12:15)
at Object.replaceSourceFileForFilePathMove (/Users/vincent/.config/yarn/global/node_modules/ts-morph/dist/manipulation/manipulations/replaction.js:64:22)
at SourceFile._moveInternal (/Users/vincent/.config/yarn/global/node_modules/ts-morph/dist/compiler/ast/module/SourceFile.js:273:24)
at SourceFile.move (/Users/vincent/.config/yarn/global/node_modules/ts-morph/dist/compiler/ast/module/SourceFile.js:246:19)
at tsAstProject.getSourceFiles.forEach.sourceFile (/Users/vincent/.config/yarn/global/node_modules/js-to-ts-converter/dist/converter/convert.js:38:24)
at Array.forEach (<anonymous>)
at Object.convert (/Users/vincent/.config/yarn/global/node_modules/js-to-ts-converter/dist/converter/convert.js:29:35)
at doConvert (/Users/vincent/.config/yarn/global/node_modules/js-to-ts-converter/dist/js-to-ts-converter.js:62:22)
at Object.convertJsToTsSync (/Users/vincent/.config/yarn/global/node_modules/js-to-ts-converter/dist/js-to-ts-converter.js:40:35)
at Object.<anonymous> (/Users/vincent/.config/yarn/global/node_modules/js-to-ts-converter/dist/cli.js:57:22)
Tried running with npx or by installing globally.
Tried running at the root of a large project and in a directory with only a single .js file.
In both cases the script hangs at the renaming step.
Here's the tail of the output:
info:
Converting source files... This may take anywhere from a few minutes to
tens of minutes or longer depending on how many files are being
converted.
info: Adding property declarations to JS Classes...
verbose: Parsing JS classes in the codebase...
verbose: Updating class 'MyDocument' in '...../src/pages/_document.js'
verbose: Adding property declarations for properties: ''
info: Renaming .js files to .ts
No further output after this step. Waiting for several minutes with no indication of progress. No files are changed.
Can get a weird build error when using ng-packagr on an Angular codebase (Angular 6 with CLI 6.0.8) that doesn't have type annotations on function parameters. Figure this would be fine to do to add the 'any' type for the moment on parameters which seems to fix this issue
function myFn( arg1, arg2 ) {}
Should become:
function myFn( arg1: any, arg2: any ) {}
Will help for people to enable the "noImplicitAny": true
option as well.
In reference to #12
I've noticed a couple of components were converted from js to ts where it should be tsx, and here's the code:
import React from "react";
import { Platform, StyleSheet } from "react-native";
import type { ColorProp } from "react-native/Libraries/StyleSheet/ColorPropType";
import { Ionicons as Ionicon } from "@expo/vector-icons";
// import colors, fonts
import Colors from "../../Theme/Colors";
// Icon Config
const ICON_COLOR = Colors.black;
const ICON_SIZE = 22;
// Icon Styles
const styles = StyleSheet.create({
icon: {
alignSelf: "center",
textAlign: "center"
}
});
// Icon Props
type Props = {
color: ColorProp,
name: string,
size: number
};
// Icon
const Icon = ({ color = ICON_COLOR, name, size = ICON_SIZE }: Props) => {
const iconSize = Platform.OS === "ios" ? size + 2 : size;
return (
<Ionicon
name={name}
color={color}
size={iconSize}
style={[
{
height: iconSize,
width: iconSize
},
styles.icon
]}
/>
);
};
export default Icon;
hey, when i run this script on about 1000 Js files, git tracked lot many file as rename, but for about 150 files git says .js
files are deleted and created new .ts
files
Is there any way we can preserve git history ?
Any method I can run once to convert all of js files in my project?
Try an Iterative Solution
`/usr/local/lib/node_modules/js-to-ts-converter/node_modules/ts-morph/dist/ts-morph.js:2274
throw new ManipulationError(sourceFile.getFilePath(), oldFileText, newFileText, message);
^
Error: Manipulation error: Maximum call stack size exceeded
-- Details --
Path: /home/shalaga44/WebstormProjects/telehealth/src/ts/matx/components/Breadcrumb.tsx
Text: "import React from \"react\";\nimport { Icon, Breadcrumbs, Hidden } from \"@material-ui/core\";\nimport { NavLink } from \"react-router-dom\";\n\nconst Breadcrumb = ({ routeSegments }) => {\n return (\n <div className=\"flex flex-wrap items-center\">\n {routeSegments ? (\n <Hidden xsDown>\n <h4 className=\"m-0 pb-1px text-16 capitalize align-middle\">\n {routeSegments[routeSegments.length - 1][\"name\"]}\n </h4>\n <h4 className=\"m-0 pb-3px ml-2 text-hint\">|</h4>\n </Hidden>\n ) : null}\n <Breadcrumbs\n separator={<Icon className=\"text-hint\">navigate_next</Icon>}\n className=\"flex items-center position-relative\"\n >\n <NavLink to=\"/\">\n <Icon className=\"align-middle ml-2 mb-1\" color=\"primary\">\n home\n </Icon>\n </NavLink>\n {routeSegments\n ? routeSegments.map((route, index) => {\n return index !== routeSegments.length - 1 ? (\n <NavLink key={index} to={route.path}>\n <span className=\"capitalize text-muted\">{route.name}</span>\n </NavLink>\n ) : (\n <span key={index} className=\"capitalize text-muted\">\n {route.name}\n </span>\n );\n })\n : null}\n </Breadcrumbs>\n </div>\n );\n};\n\nexport default Breadcrumb;\n"
Stack: RangeError: Maximum call stack size exceeded
at visitNodes (/usr/local/lib/node_modules/js-to-ts-converter/node_modules/@ts-morph/common/node_modules/typescript/lib/typescript.js:27033:24)
at forEachChild (/usr/local/lib/node_modules/js-to-ts-converter/node_modules/@ts-morph/common/node_modules/typescript/lib/typescript.js:27275:24)
at gatherPossibleChildren (/usr/local/lib/node_modules/js-to-ts-converter/node_modules/@ts-morph/common/node_modules/typescript/lib/typescript.js:27547:13)
at Object.forEachChildRecursively (/usr/local/lib/node_modules/js-to-ts-converter/node_modules/@ts-morph/common/node_modules/typescript/lib/typescript.js:27539:56)
at Object.setParentRecursive (/usr/local/lib/node_modules/js-to-ts-converter/node_modules/@ts-morph/common/node_modules/typescript/lib/typescript.js:19052:12)
at fixupParentReferences (/usr/local/lib/node_modules/js-to-ts-converter/node_modules/@ts-morph/common/node_modules/typescript/lib/typescript.js:28082:16)
at parseSourceFileWorker (/usr/local/lib/node_modules/js-to-ts-converter/node_modules/@ts-morph/common/node_modules/typescript/lib/typescript.js:27961:17)
at Object.parseSourceFile (/usr/local/lib/node_modules/js-to-ts-converter/node_modules/@ts-morph/common/node_modules/typescript/lib/typescript.js:27798:26)
at Object.createSourceFile (/usr/local/lib/node_modules/js-to-ts-converter/node_modules/@ts-morph/common/node_modules/typescript/lib/typescript.js:27598:29)
at Object.createLanguageServiceSourceFile (/usr/local/lib/node_modules/js-to-ts-converter/node_modules/@ts-morph/common/node_modules/typescript/lib/typescript.js:143700:29)
at throwError (/usr/local/lib/node_modules/js-to-ts-converter/node_modules/ts-morph/dist/ts-morph.js:2274:19)
at doManipulation (/usr/local/lib/node_modules/js-to-ts-converter/node_modules/ts-morph/dist/ts-morph.js:2272:9)
at replaceSourceFileForFilePathMove (/usr/local/lib/node_modules/js-to-ts-converter/node_modules/ts-morph/dist/ts-morph.js:2701:5)
at SourceFile._moveInternal (/usr/local/lib/node_modules/js-to-ts-converter/node_modules/ts-morph/dist/ts-morph.js:12682:9)
at SourceFile.move (/usr/local/lib/node_modules/js-to-ts-converter/node_modules/ts-morph/dist/ts-morph.js:12658:19)
at tsAstProject.getSourceFiles.forEach.sourceFile (/usr/local/lib/node_modules/js-to-ts-converter/dist/converter/convert.js:44:24)
at Array.forEach (<anonymous>)
at Object.convert (/usr/local/lib/node_modules/js-to-ts-converter/dist/converter/convert.js:33:35)
at doConvert (/usr/local/lib/node_modules/js-to-ts-converter/dist/js-to-ts-converter.js:85:22)
at Object.convertJsToTsSync (/usr/local/lib/node_modules/js-to-ts-converter/dist/js-to-ts-converter.js:63:35)`
Is there away to get parameter types info from JSDoc comments?
This would be very powerful.
JavaScript
/**
* Clamp a number between 2 values.
*
* @param {number} value - Value to clamp.
* @param {number} [min=0] - Minumum value.
* @param {number} [max=1] - Maximum value.
*
* @returns {number}
*/
static clamp(value, min = 0, max = 1) {
return MathUtils.clamp(value, min, max);
}
TypeScript
/**
* Clamp a number between 2 values.
*
* @param {number} value - Value to clamp.
* @param {number} [min=0] - Minumum value.
* @param {number} [max=1] - Maximum value.
*
* @returns {number}
*/
static clamp(value: number, min: number = 0, max: number = 1) {
return MathUtils.clamp(value, min, max);
}
This error frankly makes no sense.
File in question being converted
Node version: 16.14.0
Error:
$ npx js-to-ts-converter ./src/
info: Processing directory: '/home/kainoa/Documents/zer0bin/frontend/src'
info: Processing the following source files:
info: /home/kainoa/Documents/zer0bin/frontend/src/index.js
info:
Converting source files... This may take anywhere from a few minutes to
tens of minutes or longer depending on how many files are being
converted.
info: Adding property declarations to JS Classes...
verbose: Parsing JS classes in the codebase...
info: Renaming .js files to .ts
info: Making parameters optional for calls that supply fewer args than function parameters...
verbose: Beginning routine to mark function parameters as optional when calls exist that supply fewer args than parameters...
verbose: Parsing function/method/constructor calls from codebase.
verbose: Finding all calls to class constructors...
verbose: Processing classes in source file: /home/kainoa/Documents/zer0bin/frontend/src/index.ts
verbose: Finding all calls to functions/methods...
verbose: Processing functions/methods in source file: /home/kainoa/Documents/zer0bin/frontend/src/index.ts
verbose: Looking for calls to the function: 'postPaste'
verbose: Looking for calls to the function: 'getPaste'
/home/kainoa/.npm/_npx/adc222a32f8aa038/node_modules/@ts-morph/common/node_modules/typescript/lib/typescript.js:2472
throw e;
^
Error: Debug Failure. Expected 3 === 1. Registered script kind should match new script kind.
at getOrCreateSourceFileByPath (/home/kainoa/.npm/_npx/adc222a32f8aa038/node_modules/@ts-morph/common/node_modules/typescript/lib/typescript.js:144057:34)
at Object.getOrCreateSourceFile [as getSourceFile] (/home/kainoa/.npm/_npx/adc222a32f8aa038/node_modules/@ts-morph/common/node_modules/typescript/lib/typescript.js:144015:24)
at findSourceFile (/home/kainoa/.npm/_npx/adc222a32f8aa038/node_modules/@ts-morph/common/node_modules/typescript/lib/typescript.js:104403:29)
at /home/kainoa/.npm/_npx/adc222a32f8aa038/node_modules/@ts-morph/common/node_modules/typescript/lib/typescript.js:104280:85
at getSourceFileFromReferenceWorker (/home/kainoa/.npm/_npx/adc222a32f8aa038/node_modules/@ts-morph/common/node_modules/typescript/lib/typescript.js:104247:34)
at processSourceFile (/home/kainoa/.npm/_npx/adc222a32f8aa038/node_modules/@ts-morph/common/node_modules/typescript/lib/typescript.js:104280:13)
at processRootFile (/home/kainoa/.npm/_npx/adc222a32f8aa038/node_modules/@ts-morph/common/node_modules/typescript/lib/typescript.js:104103:13)
at /home/kainoa/.npm/_npx/adc222a32f8aa038/node_modules/@ts-morph/common/node_modules/typescript/lib/typescript.js:103021:60
at Object.forEach (/home/kainoa/.npm/_npx/adc222a32f8aa038/node_modules/@ts-morph/common/node_modules/typescript/lib/typescript.js:382:30)
at Object.createProgram (/home/kainoa/.npm/_npx/adc222a32f8aa038/node_modules/@ts-morph/common/node_modules/typescript/lib/typescript.js:103021:16)
I'm not seeing the tool to infer types form usage.. And IMO this should be the basic feature for a tool like this. I see you have focused more on code tranpilation like class declaration synyax, I think the most important part is being able to add acceptable types to variables , parameters, return types, etc (and not just add "any" to everything. So I wanted to give you a tip:
Fortunately the compiler language service is capable of inferring times for most of variables, parameters, etc. I found out it has LOTS of code-fixes that you can apply programatically. These are some examples (using ts-morph) library which provides an higher API, but it's also accomplished with compiler API directly:
This is a typescript-plugin that applies / suggests all codefixes available in the file tying suggestions in all ranges:
https://github.com/cancerberoSgx/typescript-plugins-of-mine/blob/master/typescript-plugin-all-ts-fixes-and-refactors/src/supportedCodeFixes.ts
You might find interesting this snippet that prints all code-fixes and refactors codes, names and descriptions:
This one has a inferTypesFromUsage() function that is what I just suggested to add in your lib:
convert require to import:
these is a test that runs the for remove all unused variables ode fix:
Hope it helps! feel free to use the library or code. thanks! keep ip up!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.