Front-end code automatic conversion method and device based on command line interface, medium and product

Through the front-end automatic code conversion method based on the command line interface, script, template and style code snippets in Vue files are parsed and converted, and the problems of low manual conversion efficiency and error-proneness are solved, and efficient and accurate code conversion is achieved.

CN119668625AActive Publication Date: 2025-03-21BEIJING QINGWANG TECH CORP
View PDF 7 Cites 0 Cited by

Patent Information

Application Number
CN202411730390.8
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2024-11-29
Publication Date
2025-03-21
Estimated Expiration
2044-11-29

AI Technical Summary

Technical Problem

Manually converting Vue files to TypeScript JSX files is a tedious and error-prone task, resulting in low development efficiency and high probability of errors.

Method used

It provides a front-end code automatic conversion method based on the command line interface. It parse script, template and style code snippets in Vue files through the parseComponent API, and uses TypeScript, @vue/compiler-dom and PostCSS tool libraries to convert code separately, and finally generates TSX files and SCSS module files.

Benefits of technology

The automatic conversion process is realized, the efficiency of the conversion file is improved, the probability of conversion errors is reduced, and the consistency of the converted code in function, logic and style is ensured.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN119668625A_ABST
    Figure CN119668625A_ABST
Patent Text Reader

Abstract

The invention discloses a front-end code automatic conversion method and device based on a command line interface, a medium and a product, and relates to the field of front-end code automatic conversion. The method comprises the steps that v2j is input into the command line interface, and a command line tool is started; on the basis of the command line tool, according to command line parameters input by a user, a script code snippet, a template code snippet and a stack code snippet in a Vue file are analyzed by means of parseCompentAPI (Application Program Interface); the method comprises the following steps of: acquiring three code snippets, respectively converting the three code snippets by adopting different tool libraries to generate three converted code snippets, performing mixing processing on the converted template code snippets and the converted script code snippets, and converting the mixed code snippets and the converted script code snippets into new code files. According to the method and the device, the Vue file can be automatically converted into the TSX file in stages only by executing a simple command through the command line tool, so that the development efficiency of the converted file is improved.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present application relates to the field of automatic front-end code conversion, and in particular to a method, device, medium and product for automatic front-end code conversion based on a command line interface. Background Art

[0002] With the continuous development of front-end technology, Vue.js, as a progressive JavaScript framework, has been widely used in front-end development. Vue.js is an ideal choice for developing single-page applications (SPA) because of its ease of use, high flexibility and strong community support. However, as the scale and complexity of the project increase, the traditional Vue template syntax may have certain limitations in type checking and code maintainability.

[0003] At the same time, TypeScript (TS), as a superset of JavaScript, has static type checking capabilities and more complete development tool support. It can not only effectively improve the maintainability of the code, but also greatly improve the development efficiency of R&D engineers. Therefore, it is gradually being widely used in large projects.

[0004] In this context, JSX and TSX, as important tools for front-end development, are gradually gaining attention and use from developers.

[0005] JSX (JavaScriptXML) is a syntax extension of JavaScript, commonly used in React development. JSX allows developers to write XML-like code in JavaScript, making it more intuitive to build user interfaces. It embeds HTML syntax directly into JavaScript code, making the code structure clear and easy to understand.

[0006] TSX is a syntax extension of TypeScript, similar to JSX, but supports TypeScript's static type checking. TSX files usually have a .tsx suffix, allowing developers to write JSX-like code in TypeScript and enjoy the type checking and other advanced features brought by TypeScript. TSX combines the advantages of TypeScript and JSX, maintaining the intuitiveness of the code while improving the security and maintainability of the code.

[0007] In actual front-end development work, more and more projects are gradually migrating from pure Vue.js architecture to Vue.js projects using TypeScript (i.e. Vue+TS or Vue+TSX), especially Vue+TSX projects, which have the following advantages:

[0008] Static type checking: TSX files support TypeScript's static type checking, which can capture type errors during the compilation phase, reduce runtime errors, and improve code reliability and maintainability.

[0009] Development tool support: TypeScript has rich development tool support, including smart prompts, code completion, refactoring tools, etc., which help improve development efficiency and code quality.

[0010] Code quality and maintainability: TypeScript's strong type system makes the code more self-documenting, facilitating team collaboration and code maintenance, especially in large projects.

[0011] Community and ecosystem: As TypeScript becomes more popular, more and more open source libraries and projects are beginning to support or prioritize TypeScript. Using TSX files can help you better utilize these resources.

[0012] However, manually converting a large number of Vue files (.vue) to TypeScriptJSX files (.tsx) is a tedious and error-prone task. This not only requires developers to have dual skills in Vue and TypeScript, but also to carefully handle various details that may arise during the conversion process, such as type definitions, component properties, and lifecycle method conversions. If not handled properly, it is easy to introduce new errors, causing the project to fail to run normally. In addition, manually converting a large number of files will consume a lot of time and energy, reducing development efficiency. Summary of the invention

[0013] The purpose of this application is to provide a method, device, medium and product for automatic conversion of front-end codes based on a command line interface to solve the problems of low efficiency and easy errors in manual conversion file development.

[0014] To achieve the above objectives, this application provides the following solutions:

[0015] In a first aspect, the present application provides a method for automatic conversion of front-end code based on a command line interface, comprising:

[0016] Enter v2j in the command line interface to start the command line tool; the basic instructions of the command line tool include the path instruction of the specified configuration file, the path instruction of the file to be processed, and the stage instruction to be processed; the stages to be processed include the "style" stage, the "template" stage, and the "script" stage;

[0017] Based on the command line tool, according to the command line parameters input by the user, the parseComponent API is used to parse the script code snippet, template code snippet and style code snippet in the Vue file;

[0018] Based on the TypeScript class component of the TypeScript tool library, using a script code converter to perform code conversion on the script code fragment to generate a converted script code fragment;

[0019] Based on the @vue / compiler-dom tool library and the @babel tool library, the template code snippet is converted by using the template code converter to generate a converted template code snippet;

[0020] Based on the PostCSS tool library and the PostCSS-SCSS plug-in, the style code fragment is converted by using a style code converter to generate a converted style code fragment; the style code converter is a SCSS preprocessor;

[0021] The converted template code snippet and the converted style code snippet are combined and processed, and the combined code snippet and the converted script code snippet are converted into a new code file; the new code file includes a TSX file and a SCSS module file, wherein the TSX file is used to store the converted script code snippet and template code snippet, and the SCSS module file is used to store the converted style code snippet; the command line parameters include a configuration file path parameter, a to-be-converted file path list parameter, and a code conversion necessary processing stage parameter.

[0022] In a second aspect, the present application provides a computer device, comprising: a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor executes the computer program to implement any of the above-mentioned methods for automatic front-end code conversion based on a command line interface.

[0023] In a third aspect, the present application provides a computer-readable storage medium having a computer program stored thereon, which, when executed by a processor, implements any of the above-mentioned methods for automatic front-end code conversion based on a command line interface.

[0024] In a fourth aspect, the present application provides a computer program product, including a computer program, which, when executed by a processor, implements any of the above-mentioned methods for automatic front-end code conversion based on a command line interface.

[0025] According to the specific embodiments provided by the present application, the present application discloses the following technical effects: in order to improve the efficiency and quality of code migration, the present application starts the command line tool through the command line interface, and based on the command line tool, uses the parseComponentAPI to parse the script code snippets, template code snippets and style code snippets in the Vue file according to the command line parameters entered by the user; and through the TypeScript tool library, @vue / compiler-dom tool library and @babel tool library, as well as the PostCSS tool library and the PostCSS-SCSS plug-in, the script code snippets, template code snippets and style code snippets are converted respectively, and finally, the converted script code snippets, the converted template code snippets and the converted style code snippets are blended to generate a new code file; the new code file is the TSX file and the SCSS module file. The present application only executes a simple command (that is, the command line parameters entered by the user) through the command line tool to automatically convert the Vue file into the TSX file in stages, thereby improving the development efficiency of the converted file and reducing the probability of conversion errors. BRIEF DESCRIPTION OF THE DRAWINGS

[0026] In order to more clearly illustrate the embodiments of the present application or the technical solutions in the prior art, the drawings required for use in the embodiments will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the present application. For ordinary technicians in this field, other drawings can be obtained based on these drawings without paying creative work.

[0027] Figure 1 This is a flow chart of a method for automatic conversion of front-end codes based on a command line interface in one embodiment of the present application. DETAILED DESCRIPTION

[0028] The following will be combined with the drawings in the embodiments of the present application to clearly and completely describe the technical solutions in the embodiments of the present application. Obviously, the described embodiments are only part of the embodiments of the present application, not all of the embodiments. Based on the embodiments in the present application, all other embodiments obtained by ordinary technicians in this field without creative work are within the scope of protection of this application.

[0029] In order to make the above-mentioned objects, features and advantages of the present application more obvious and easy to understand, the present application is further described in detail below with reference to the accompanying drawings and specific implementation methods.

[0030] There are some tools and libraries on the market that can help developers use TypeScript in Vue projects. For example, Vue officially provides the Vue CLI tool, which supports the creation and management of Vue+TS projects; there are also some community-contributed tools that can help developers gradually introduce TypeScript into Vue projects. However, these tools are mainly for supporting new projects, or gradually introducing TypeScript into existing projects, rather than specifically for automatic conversion of Vue files to TSX files.

[0031] The following are some existing solutions known to the inventor:

[0032] Vue CLI: Vue CLI is a powerful scaffolding tool officially provided by Vue, which supports the creation of Vue+TypeScript projects. Although Vue CLI provides preliminary TypeScript support, it is more suitable for the creation and configuration of new projects and does not have the function of automatically converting existing Vue files to TSX files.

[0033] Community tools: Some community-contributed tools and plugins can help developers introduce TypeScript into Vue projects. For example, tools such as vue-property-decorator and vue-class-component can help developers write TypeScript code in Vue projects. However, these tools are mainly for assisting in writing and managing TypeScript code, rather than automating the conversion of existing Vue files.

[0034] In summary, there is currently no mature and widely used tool for the automatic conversion of Vue files to TSX files. Therefore, existing solutions mainly rely on manual conversion or writing custom scripts, which have problems such as high development cost, low efficiency, and easy errors.

[0035] The method for automatic conversion of front-end codes based on a command line interface provided in an embodiment of the present application is executed by a computer device, specifically, it can be executed by a computer device such as a terminal or a server alone, or it can be executed by a terminal and a server together, and the method includes the following steps 101 to 106. Among them:

[0036] Step 101: Enter v2j in the command line interface to start the command line tool; the basic instructions of the command line tool include instructions for specifying the path of the configuration file, instructions for specifying the path of the file to be processed, and instructions for specifying the stage to be processed; among which, the stages to be processed include the "style" stage, the "template" stage, and the "script" stage.

[0037] Step 102: Based on the command line tool, according to the command line parameters input by the user, the script code snippet, the template code snippet and the style code snippet in the Vue file are parsed using parseComponentAPI.

[0038] Step 103: Based on the TypeScript class component of the TypeScript tool library, use a script code converter to perform code conversion on the script code fragment to generate a converted script code fragment.

[0039] Step 104: Based on the @vue / compiler-dom tool library and the @babel tool library, the template code snippet is converted by using a template code converter to generate a converted template code snippet.

[0040] Step 105: Based on the PostCSS tool library and the PostCSS-SCSS plug-in, use a style code converter to perform code conversion on the style code fragment to generate a converted style code fragment; the style code converter is a SCSS preprocessor.

[0041] Step 106: Blend the converted template code snippet and the converted style code snippet, and convert the blended code snippet and the converted script code snippet into a new code file; the new code file includes a TSX file and a SCSS module file, wherein the TSX file is used to store the converted script code snippet and template code snippet, and the SCSS module file is used to store the converted style code snippet; the command line parameters include a configuration file path parameter, a to-be-converted file path list parameter, and a code conversion required processing stage parameter.

[0042] Since the template, script, and style parts of a Vue file each have unique syntax and structure, different conversion strategies are required to achieve accurate conversion to TSX files. The three parts each have unique syntax and structure as follows:

[0043] 1. Grammatical Differences:

[0044] The template part uses Vue's unique template syntax and needs to be converted to JSX syntax.

[0045] The script part needs to be converted from JavaScript to TypeScript and adapt to the lifecycle methods and property definitions of the Vue component in the TSX environment.

[0046] The style part needs to be converted from Vue scoped styles to CSS Modules.

[0047] 2. Conversion complexity:

[0048] The conversion of each part involves different syntax parsers and conversion rules. Processing each part separately can reduce the complexity of the overall conversion.

[0049] 3. Error Isolation:

[0050] Treating them separately makes it easier to locate and handle possible conversion errors in each part without affecting each other.

[0051] 4. Modular processing:

[0052] Separate processing is conducive to realizing a modular conversion process and facilitating subsequent maintenance and upgrading of each conversion module.

[0053] 5. Performance optimization:

[0054] Separate processing allows the conversion process to be performed in parallel, improving conversion efficiency.

[0055] By processing these three parts separately, this command tool can more accurately and efficiently convert Vue files into TSX files that conform to TypeScript and JSX syntax, while ensuring the consistency and correctness of functions, logic, and styles. This approach not only improves the accuracy and efficiency of the conversion, but also enhances the maintainability and readability of the converted code.

[0056] For the convenience of developers, this application has designed a simple and easy-to-use command line tool for converting Vue files to TSX files. The tool provides a variety of configuration options and functions to ensure flexible application in different projects. Its specific design is as follows:

[0057] Command line entry: This application sets a concise and clear tool name: v2j. Users can start the conversion tool by entering this name in the command line. In order to parse the commands and parameters entered by the user and schedule the corresponding code processing logic, this application creates a core entry file (cli.js), which will be responsible for the above core interactive functions.

[0058] Basic commands: This application defines the basic commands of the tool, which are used to trigger file conversion:

[0059] v2j -f {vue filepath} -c {config filepath} -s {stages, transformations to be performed}

[0060] Among them, -f is a required parameter, which is used to specify the Vue file that needs to be converted.

[0061] The specific meanings of the parameters in the command are as follows:

[0062] 1. ˋv2jˋ: The main command name of the tool, which stands for the abbreviation of "Vue to JSX".

[0063] 2. -f{vue filepath}:

[0064] -f: file parameter flag

[0065] ˋ{vue filepath}ˋ: The path of the Vue file that needs to be converted

[0066] This is a required parameter that specifies the location of the Vue file to be converted.

[0067] 3. -c {config file path}:

[0068] -c: Configuration parameter flag

[0069] ˋ{config file path}ˋ: Optional configuration file path for customizing the conversion process

[0070] 4.ˋ-s{stages}ˋ:

[0071] -s: Stages parameter flag

[0072] ˋ{stages}ˋ: Optional parameter used to specify the specific transformation stage to be performed

[0073] In this command structure, the Vue file path following -f is the only required parameter, formally known as the "Input File Path Parameter". Other parameters (-c and -s) are optional and are used to further customize and control the conversion process.

[0074] Optional parameters:

[0075] -c, --config: Specify the path to the configuration file

[0076] -f, --files: specifies the file path to be processed. Multiple files are separated by commas.

[0077] -s, --stages: specifies the stage to be processed. It supports three stages: template, style, and script, separated by commas. If not passed, all processes will be executed by default.

[0078] -h, --help: Display detailed help information for this tool

[0079] 1. Configuration file parameters:

[0080] Short format: -c (configuration abbreviation)

[0081] Long format: ˋ--configˋ (full name of configuration)

[0082] Function: Specify the path of the configuration file

[0083] 2. File path parameters:

[0084] Short format: -f (file abbreviation)

[0085] Long format: ˋ--filesˋ(full file name)

[0086] Function: Specify the file path to be processed. Multiple files are separated by commas.

[0087] 3. Processing stage parameters:

[0088] Short form: ˋ-sˋ (phase abbreviation)

[0089] Long format: ˋ--stagesˋ(full name of the stage)

[0090] Function: Specify the stage to be processed. It supports three stages: template, style, and script, separated by commas.

[0091] Default behavior: If not passed, all processes will be executed by default

[0092] 4. Help information parameters:

[0093] Short form: ˋ-hˋ (abbreviation for help)

[0094] Long format: ˋ--helpˋ (full name of help)

[0095] Function: Display detailed help information of this tool

[0096] Each parameter has two ways of expressing it: short form (single letter) and long form (full word), and users can choose to use it according to personal preference. The short form uses a single hyphen (ˋ-ˋ), while the long form uses a double hyphen (ˋ--ˋ) as a prefix.

[0097] When the user enters the above command line code in the command line terminal, the code conversion process will be started, the specified Vue file will be read, and the final TSX file and SCSS module file will be generated.

[0098] By default, new files will be generated in the same directory as the original Vue file. The following will describe in detail the specific execution steps that occur during the code conversion process:

[0099] (I) Command line parameter parsing.

[0100] As described above, the command tool of the present application supports carrying parameters in the command line code to customize the code conversion process. This step requires pre-parsing the parameters specified by the user to guide subsequent code execution behavior.

[0101] This application uses the command line parameter parsing library Yargs to parse the commands and parameters entered by the user. The library provides a concise API that can easily define and parse command line parameters.

[0102] The tool described in this application uses the command line parameter parsing library to first define the command line parameters supported by the tool described in this application: c (config) is used to receive the configuration file path specified by the user; f (files) is used to receive the file path to be converted specified by the user; s (stages) is used to receive the code conversion must be processed stage specified by the user; h (help) is used to respond to the user's request for help information. Finally, at the end of the above code snippet, the command line parameter information is obtained by chaining the parseAPI call.

[0103] In an exemplary embodiment, the step 102 also includes: a configuration file path parameter verification process, a to-be-converted file path list parameter verification process, and a code conversion necessary processing stage parameter verification process.

[0104] The configuration file path parameter verification process is as follows: verify the configuration file path parameter. If the user does not specify the configuration file path parameter, read the USER_DEFINED_CONFIG_PATH variable configured by the user in the running environment, and use the USER_DEFINED_CONFIG_PATH variable as the configuration file path; verify whether the configuration file path really exists, and call the built-in import method of the running environment to load and read the configuration file path; if the configuration file path does not exist, the file content reading fails, or the file content is empty, terminate the process and output different error messages in the terminal: "Configuration file not found", "Configuration file content reading failed", or "Configuration file content is empty"; if the configuration file path exists, and the configuration file path file The configuration content is read successfully, and the read configuration content is temporarily stored in the global variable to complete the configuration file path parameter verification process; if the user has neither specified the configuration file path parameter in the command line nor configured the USER_DEFINED_CONFIG_PATH environment variable in the running environment, then in the current working directory where the user executes the command line, the built-in file creation API and file writing API of the code running environment are automatically called to generate a configuration file named "vue-sfc-to-jsx.config.ts"; the content of the configuration file is a built-in default configuration code; if the configuration file is written successfully, repeat the above configuration file path parameter verification process; if the configuration file fails to be written, terminate the process and output the error message "Configuration file writing failed" in the terminal.

[0105] The parameter verification process of the file path list to be converted is as follows: if the user does not specify the file path list parameter to be converted, the process is directly terminated, and an error message "No file to be processed is specified" is output in the terminal; if the user specifies the file path list parameter to be converted, the parameter value of the string type is cut through the built-in API of the operating environment, the cutting point is an English half-width comma, and a file path list is obtained; the file path list is traversed, the leading and trailing spaces of the file path string are processed one by one, and it is verified whether the processed file path is a legal Vue file path; if no legal Vue file path is found after the verification process, the process is directly terminated, and an error message "No legal Vue file path is specified" is output in the terminal; if there are both legal Vue file paths and illegal Vue file paths, the next process is continued to be executed, and a warning message "There is an illegal path: {path A}|{path B}|..." is output in the terminal; if all are legal Vue file paths, the next process is continued to be executed normally; the file path list to be converted that is verified to be legal is temporarily stored in a global variable.

[0106] The code conversion must-process stage parameter verification process is as follows: if the user does not specify the code conversion must-process stage parameter, the code conversion must-process stage parameter verification process is skipped directly, and in the subsequent conversion process, all-stage conversion is performed, and the all-stage list ["style", "script", "template"] is temporarily stored in the global variable; if the user specifies the code conversion must-process stage parameter, the parameter value of the string type is cut through the built-in API of the operating environment, and the cutting point is the English half-width comma, and a stage list is obtained; the stage list is traversed, the leading and trailing spaces of the stage string are processed one by one, and it is verified whether the processed stage is a legal stage; the legal stage includes [ "style", "script", "template"]; "style" is the "style" stage, "template" is the "template" stage, and "script" is the "script" stage; if no legal stage is found after processing and verification, the process is terminated directly, and the error message "No legal stage specified" is output to the terminal; if there are both legal and illegal stages, continue to execute the next process, and output the warning message "Illegal stage will be ignored: {path A}|{path B}|..." in the terminal; if all are legal stages, continue to execute the next process normally; the list of stages verified as legal is temporarily stored in the global variable.

[0107] Further, (ii) command line parameter check.

[0108] Based on the above (a), this application has obtained the command line parameters input by the user, but due to the uncertainty of the user's command line parameter input, these parameters need to be checked and verified through this step before officially starting the conversion process.

[0109] First, this application will verify the configuration file path parameter c (config). In this step of verification, if the user does not specify the configuration file path, this application will read the USER_DEFINED_CONFIG_PATH variable configured by the user in the running environment and use it as the configuration file path. Subsequently, this step will verify whether the specified configuration file path actually exists, and will try to call the built-in import method of the running environment to load and read. If the file path does not exist / the file content fails to read / the file content is empty, this application will terminate the process and output different error messages in the terminal: "Configuration file not found" / "Configuration file content reading failed" / "Configuration file content is empty"; if the file path exists and the configuration content in the file is read successfully, the read configuration content will be temporarily stored in the global variable for use in subsequent processes.

[0110] In addition to the above content, this verification step also has the following built-in fallback solution: If the user does not specify the configuration file path parameter in the command line nor configure the USER_DEFINED_CONFIG_PATH environment variable in the running environment, the file creation and writing API built into the code running environment will be automatically called to generate a configuration file in the current working directory where the user executes the command line. The file name is "vue-sfc-to-jsx.config.ts" and the content is a default configuration code built into this application. After successful writing, the above reading operation will be repeated. If the file writing fails, this application will terminate the process and output the error message "Configuration file writing failed" in the terminal.

[0111] Secondly, this application will verify the file path list parameter f(files) to be converted, which is a necessary parameter for the subsequent code execution of this application. It allows multiple file paths to be specified at the same time, and the paths must be separated by English half-width commas. In this step of verification, if the user does not specify this parameter, this application will directly terminate the process and output an error message "No file to be processed" in the terminal. If the user specifies this parameter, this application will cut the parameter value of the string type through the built-in API of the operating environment, and the cutting point is the English half-width comma, and finally obtain a file path list, such as cutting a string such as "a.doc, b.doc" with an English half-width comma to obtain a file path list ["a.doc", "b.doc"].

[0112] This application will traverse the file path list, process the leading and trailing spaces of the file path string one by one, and verify whether the processed file path is a legal Vue file path. If there is no legal Vue file path after processing and verification, this application will directly terminate the process and output the error message "No legal Vue file path specified" in the terminal; if there are both legal Vue file paths and illegal Vue file paths, this application will continue to execute, but will output a warning message in the terminal "There is an illegal path: {path A}|{path B}|..."; if all are legal paths, this application will continue to execute normally. This step will eventually temporarily store the list of file paths to be processed that have been verified as legal into a global variable for use in subsequent processes.

[0113] Finally, this application will verify the code conversion must process the stage parameter s (stages). In this step of verification, if the user does not specify this parameter, this application will directly skip this verification step and perform full-stage conversion in the subsequent conversion process. If the user specifies this parameter, similar to the processing of the file path parameter, this application will cut the parameter value of the string type through the built-in API of the operating environment, and the cutting point is the English half-angle comma, and finally obtain a stage list. This application will traverse the stage list, process the leading and trailing spaces of the stage string one by one, and verify whether the processed stage is a legal stage-the only built-in legal stages in this application are ["style", "script", "template"]. If there is no legal stage after processing and verification, this application will directly terminate the process and output the error message "No legal stage specified" in the terminal; if there are both legal stages and illegal stages, this application will continue to execute, but will output a warning message in the terminal "Illegal stage will be ignored: {path A}|{path B}|..."; if all are legal stages, this application will continue to execute normally. This step will eventually store the read stage list into a global variable. If the user does not specify this parameter, the entire stage list ["style", "script", "template"] will be stored into this variable for use in subsequent processes.

[0114] Before starting to introduce the specific template, script, and style code conversion process, this application first explains the technical core of this application: AST-based conversion.

[0115] The core technology of this application is to realize the automatic conversion of Vue files to TSX files based on AST (Abstract Syntax Tree).

[0116] AST is a tree representation of the abstract syntax structure of the source code, which can clearly express the structure and components of the code. It is the basis for code parsing and conversion in this application. By building and operating AST, we can deeply understand and transform the code structure, thereby achieving accurate code conversion.

[0117] Regardless of which part of the Vue file is the template, script, or style, the unified code conversion process remains unchanged, as follows:

[0118] AST generation: Use a specific tool library to parse the code of a specific part of the Vue file and generate the corresponding abstract syntax tree (AST).

[0119] AST conversion: For different ASTs generated by different parts of the Vue file, targeted code node conversion processing is performed, which includes a series of optimization measures such as syntax improvement, redundant node merging, and expression simplification.

[0120] AST generation and output: The converted templateAST, scriptAST and styleAST are respectively converted into complete jsx code snippets, script code snippets and style code snippets. Further optimization and code formatting are then performed to ensure that the generated code snippets comply with the best practices of TypeScript and JSX.

[0121] By parsing, converting and generating around AST, the technical solution of the present application can achieve accurate and efficient conversion of Vue files. AST provides a deep understanding and operation capability of the code structure, so that the conversion process can maintain the logical consistency and readability of the code.

[0122] In an exemplary embodiment, step 103 may be replaced by the following steps.

[0123] Use the createSourceFileAPI in the TypeScript class component of the TypeScript tool library to parse the script code snippet and determine the scriptAST; the scriptAST includes all syntax nodes in the Vue file, and the syntax nodes include data, methods, calculated properties and lifecycle hooks; use the transform method in the TypeScript class component of the TypeScript tool library to traverse each syntax node in the scriptAST in a breadth-first traversal order to determine the type of each syntax node; parse different types of syntax nodes to construct a new scriptAST; based on the new scriptAST, call the printFileAPI in the TypeScript tool library to generate a converted script code snippet.

[0124] Furthermore, different types of syntax nodes are parsed to construct a new scriptAST, specifically including: if the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of the PropertyAssignment node is "name", the node initialization value corresponding to the PropertyAssignment node is taken out and temporarily stored as the component name of the subsequent new jsx code snippet; if the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of the PropertyAssignment node is "data", and the initialization value node of the PropertyAssignment node is a method node, the re of the method node is parsed. The AST node corresponding to the turn statement is retrieved, and the AST node is recursively traversed to parse out the first object property-value pair list; the typescriptcreatePropertyDeclarationAPI is called to generate a new first-class property node for each element in the first object property-value pair list as part of the subsequent new jsxAST; if the currently traversed syntax node is a MethodDeclaration node, and the name identifier string of the MethodDeclaration node is "data", the AST node corresponding to the return statement of the MethodDeclaration node is parsed, and the AST node is recursively traversed to parse out the second ... The createPropertyDeclarationAPI generates a new second-class property node for each element in the second object property-value pair list as part of the subsequent new jsx AST; if the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of the PropertyAssignment node is one of "components", "filters" or "directives", the AST nodes are temporarily stored for subsequent reuse to form part of the new jsx AST; if the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of the PropertyAssignment node is "computed", and the initialization value node of the PropertyAssignment node is an object type node, the object AST nodes are recursively traversed to parse out the property name, property calculation method and property accessor type corresponding to each calculated property;Call the createGetAccessorDeclaration method or the createSetAccessorDeclaration method to generate a new class accessor property node corresponding to the calculated property as part of the subsequent new jsx AST; if the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of the PropertyAssignment node is "methods", and the initialization value node of the PropertyAssignment node is an object type node, then recursively traverse the object AST node to parse out the method name, method input parameter, function body and modifiers corresponding to each component method; call the createMethodDeclaration method to generate a new class method node corresponding to the component method as the subsequent new jsx AST; if the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of the PropertyAssignment node is "props", and the initialization value node of the PropertyAssignment node is an object type node, then recursively traverse the object AST node to parse out the prop identifier name and prop initialization value corresponding to each component prop; call the createPropertyDeclaration method to generate a new first-class property declaration node corresponding to the component prop as part of the subsequent new jsxAST; if the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of the PropertyAssignment node is "props", and the Prope If the initialization value node of the rtyAssignment node is an array type node, the array AST nodes are traversed, and the createPropertyDeclaration method is called for the array elements to generate a new second-class property declaration node corresponding to the component prop as part of the subsequent new jsxAST; if the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of the PropertyAssignment node is "watch", and the initialization value node of the PropertyAssignment node is an object type node, the object AST nodes are recursively traversed to parse out the watcher identifier name, watcher method parameters, watcher method body, watcher object and watcher configuration corresponding to each component watcher;Call the createMethodDeclaration method to generate a new class method declaration node corresponding to the component watcher as part of the subsequent new jsx AST; if the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of the PropertyAssignment node is any of "beforeCreate", "created", "beforeMount", "mounted", "beforeUpdate", "updated", "activated", "deactivated", "beforeDestroy", "destroyed" and "errorCaptured", it means that the current node is a Vue component lifecycle hook node, and the identifier name, method parameters, method body and identifier corresponding to the lifecycle method are parsed from the Vue component lifecycle hook node; call the createMethodDeclaration method to generate a new class method declaration node corresponding to the Vue component lifecycle hook node as the subsequent new jsx AST; if the currently traversed syntax node is an ExportAssignment node, it means that the current node is a default export node, and the expression child nodes of the default export node are fully recursively traversed, and the default export node is skipped; if the currently traversed syntax node is an unprocessed node, there is no need to recursively traverse it, and only the unprocessed node is temporarily stored and reserved for subsequent use as part of the new jsxAST; the unprocessed node is an ImportDeclaration node, an ExportDeclaration node, or a VariableStatement node; a new scriptAST is constructed according to the component name of the new jsx code snippet and a part of the new jsxAST. ;

[0125] The script code converter is further described below.

[0126] In the process of converting Vue files to TSX files, the script part needs special treatment because it involves converting Vue's component logic and data management into code that conforms to TypeScript and TSX syntax. The process involves parsing the original JavaScript or TypeScript code and converting it into the form of TypeScript class components using the vue-tsx-support and vue-property-decorator tool libraries. The specific conversion steps are as follows:

[0127] 1. Parse script code:

[0128] Use the createSourceFileAPI of the TypeScript tool library typescript to parse the script code and obtain the script abstract syntax tree (AST). The scriptAST will contain all the syntax nodes in the original Vue file, including data, methods, calculated properties, lifecycle hooks, etc.

[0129] 2. Traverse the existing scriptAST and generate a new scriptAST:

[0130] This step is the most core step in the script code conversion process. Given the huge differences in the syntax before and after the script code conversion, it is extremely difficult to modify the nodes directly on the existing scriptAST. Therefore, this application adopts a solution of traversing and analyzing the scriptAST generated by the previous steps to gradually generate a new script AST. The specific process is described as follows:

[0131] First, this application uses the transform method of the TypeScript tool library typescript to recursively traverse the scriptAST generated in the above step 1. The API will traverse each syntax node of the scriptAST in breadth-first traversal order.

[0132] Since there are many different types of syntax nodes in a script code fragment, this application will also combine conditional control statements to perform different parsing processes for different types of syntax nodes to prepare for generating the final converted script code. The specific processing method is as follows:

[0133] If the currently traversed syntax node is a PropertyAssignment node, and the node's name identifier string is "name", the node initialization value corresponding to the PropertyAssignment node is taken out and temporarily stored as the component name of the subsequent new jsx code snippet.

[0134] If the currently traversed syntax node is a PropertyAssignment node, and the node's name identifier string is "data" and the node's initialization value node is a method node, then the AST node corresponding to the return statement of the method node is parsed, and it is recursively traversed to parse the object property-value pair list from it, and the typescript createPropertyDeclarationAPI is called to generate a new class property node for each list element as part of the subsequent new jsxAST.

[0135] If the currently traversed syntax node is a MethodDeclaration node, and the node's name identifier string is "data", the AST node corresponding to the return statement of the node is parsed, and it is recursively traversed to parse the object property-value pair list, and the typescript createPropertyDeclarationAPI is called to generate a new class property node for each list element as part of the subsequent new jsxAST.

[0136] If the currently traversed syntax node is a PropertyAssignment node, and the node's name identifier string is one of "components", "filters" or "directives", the AST node is temporarily stored separately for subsequent reuse to form part of the new jsxAST.

[0137] If the currently traversed syntax node is a PropertyAssignment node, and the node's name identifier string is "computed" and the node's initialization value node is an object type node, it is necessary to recursively traverse the object AST node, parse out the three types of information corresponding to each calculated property, namely the property name, property calculation method, and property accessor type, and call the createGetAccessorDeclaration or createSetAccessorDeclaration method to generate new class accessor property nodes for these calculated properties as part of the subsequent new jsxAST.

[0138] If the currently traversed syntax node is a PropertyAssignment node, and the node's name identifier string is "methods" and the node's initialization value node is an object type node, then it is necessary to recursively traverse the object AST node, parse out the four types of information corresponding to each component method, namely, method name, method input parameter, function body, and modifier, and call the createMethodDeclaration method to generate new class method nodes for these component methods as part of the subsequent new jsxAST.

[0139] If the currently traversed syntax node is a PropertyAssignment node, and the node's name identifier string is "props" and the node's initialization value node is an object type node, then you need to recursively traverse the object AST node, parse out the prop identifier name and prop initialization value corresponding to each component prop, and call the createPropertyDeclaration method to generate new class property declaration nodes for these component props as part of the subsequent new jsxAST.

[0140] If the currently traversed syntax node is a PropertyAssignment node, and the node's name identifier string is "props", and the node's initialization value node is an array type node, since the elements corresponding to the array are all prop identifier names, it is only necessary to traverse the array AST node and call the createPropertyDeclaration method for the array elements to generate new class property declaration nodes for these component props as part of the subsequent new jsxAST.

[0141] If the currently traversed syntax node is a PropertyAssignment node, and the node's name identifier string is "watch", and the node's initialization value node is an object type node, then it is necessary to recursively traverse the object AST node, parse out the watcher identifier name, watcher method parameters, watcher method body, watcher object, and watcher configuration corresponding to each component watcher, and call the createMethodDeclaration method to generate new class method declaration nodes for these component watchers as part of the subsequent new jsxAST.

[0142] If the currently traversed syntax node is a PropertyAssignment node, and the node's name identifier string is any of "beforeCreate", "created", "beforeMount", "mounted", "beforeUpdate", "updated", "activated", "deactivated", "beforeDestroy", "destroyed", and "errorCaptured", it means that the current node is a Vue component lifecycle hook node. You only need to parse the identifier name, method parameters, method body, and identifier corresponding to the lifecycle method from the node, and call the createMethodDeclaration method to generate a new class method declaration node for the lifecycle hook as part of the subsequent new jsxAST.

[0143] If the currently traversed syntax node is an ExportAssignment node, it means that the current node is the default export node, which is the core of the Vue component script code. It is necessary to perform a comprehensive recursive traversal on the expression child nodes of the node, while the node itself is skipped.

[0144] If the currently traversed syntax node is an ImportDeclaration node, ExportDeclaration node, VariableStatement node, or other unprocessed node, there is no need to recursively traverse it. Just temporarily store the node and use it as part of the new jsxAST later.

[0145] After the above recursive AST analysis combined with conditional control statements, the application will have component name information, a new class method declaration node list, a new class attribute declaration node list, and other node lists that cannot be specially processed or do not need to be processed. This information will be used to generate a new scriptAST:

[0146] First, determine whether there are any nodes named "components", "filters" or "directives" in the temporarily stored node list. If so, use createDecorator in combination with createCallExpressionAPI to generate an AST corresponding to a decorator statement of the form "@Component({components:{xxx}})" in advance; if not, just call createDecorator to generate an AST corresponding to a decorator statement of the form "@Component".

[0147] Secondly, call createModifierAPI to generate the necessary export and default modifiers for the new jsxAST.

[0148] For the jsx part of the TSX file, since it needs to be embedded in the render method of the class class to take effect, it is also necessary to call the createMethodDeclaration method in advance to generate a class method declaration node named render, and set the return node content of the method to the predefined "===========jsx here===========" placeholder string to facilitate replacing it with the real jsx code snippet in the subsequent process.

[0149] For TSX files, the component form is class component, so you need to use createClassDeclaration, createHeritageClause and createExpressionWithTypeArguments API to pass in reasonable parameters such as component name, class attribute declaration node list, class method declaration node list, etc.

[0150] Filter the temporary node list, extract the ImportDeclaration node, ExportDeclaration node, and VariableStatement node from it to form a node list, and call the updateSourceFileAPI, passing the node list and the newly generated classAST as parameters, passing it into the API as input parameters, and obtaining a new scriptAST that can be used to generate the final code.

[0151] 3. Generate a new script code snippet based on the new scriptAST:

[0152] Through the above steps, the application has obtained a new scriptAST. At this time, it only needs to call the printFileAPI provided by the typescript tool library to generate code snippets. At this point, the script code conversion is completed.

[0153] In an exemplary embodiment, step 104 may be replaced by the following steps.

[0154] Use the parseAPI of the @vue / compiler-dom tool library to parse the template code snippet to obtain templateAST; the templateAST includes all types of nodes in the component template; the types of nodes include label nodes, text nodes, instruction nodes and component nodes; traverse the templateAST, use depth-first recursive order, combine conditional control statements, perform different parsing processes on different types of marked nodes, and build a new jsxAST based on the API of the @babel tool library; based on the new jsxAST, call the generatorAPI in the @babel tool library to generate a jsx code snippet; the jsx code snippet is the converted template code snippet.

[0155] Furthermore, the templateAST is traversed, and different parsing processes are performed on different types of marked nodes using a depth-first recursive order combined with conditional control statements, and a new jsxAST is constructed based on the API of the @babel tool library, specifically including: if the currently traversed marked node is an ELEMENT node, the props attribute in the node AST is determined; the props attribute includes a list of all attribute nodes in the ELEMENT node; each attribute node in the attribute node list is classified and processed in combination with conditional control statements to determine an attribute information list; the attribute information list is traversed, and a new jsx corresponding to each element in the attribute information list is generated. AST attribute node; if the currently traversed marked node is an ELEMENT node, determine the children attribute in the node AST, recursively process the child node list of the ELEMENT node, and determine the new jsxAST node and the instruction type attribute to be processed of each child node; traverse the child node list in positive order to process the for loop instruction, call the parseExpressionAPI to convert the attribute value string into a loop expression AST, and parse the loop object and loop parameter from it, and then construct the AST node corresponding to the code of the form "{xxx.map(y=>{return child node})}" by using the jsxExpressionContainer of the @babel tool library in conjunction with multiple APIs; multiple APIs include callExpression, arrowFunctionExpression and blockStatement; among them, {xxx.map(y=>{return child node})} is an example, xxx is the "loop object" mentioned above, y is the "loop parameter" mentioned above, xxx.map is a loop statement; traverse the child node list in reverse order, group the child nodes with conditional pairing relationships, and for the child nodes contained in these groups, combine the attribute value strings of each child node to construct an AST node corresponding to the code in the form of "{a? child node 1: child node 2}"; wherein, "{a? child node 1: child node 2}" is a conditional control code block; a is the judgment condition in the conditional control statement; take out the tag attribute in the node AST, and judge whether the tag attribute is the html native tag name; if so, do not do any processing, if not, treat the ELEMENT node as a component node, and format the name of the tag attribute in upper camel case; call jsxElement API, pass the processed tag attribute name, the processed attribute node list and the processed child node list as parameters, and generate a new jsx node; if the currently traversed tag node is a TEXT node, call jsxText API generates a new jsx node for the TEXT node; if the currently traversed tag node is an INTERPOLATION node, parse the interpolation content string from the node AST, then call parseExpressionAPI to parse the INTERPOLATION node into an expression AST, and finally call jSXExpressionContainerAPI to generate a new jsx node for the INTERPOLATION node; based on the API of the @babel tool library, build a new jsxAST according to all new jsx nodes. .

[0156] The template code converter is further described below.

[0157] When converting Vue files to TSX files, the template part needs special processing because it involves the conversion from Vue's template syntax to JSX syntax, and this process requires the use of the @vue / compiler-dom tool library and the @babel tool library. The specific steps are as follows:

[0158] 1. Parse the template code:

[0159] Use the parse API of the @vue / compiler-dom tool library to parse the template code and obtain the templateAST. The templateAST will contain all types of nodes in the component template, such as label nodes, text nodes, instruction nodes, and component nodes.

[0160] 2. Traverse the existing templateAST and generate a new jsxAST:

[0161] This step is the most core step in the template code conversion process. Given the huge differences in syntax before and after template code conversion, and the different tool libraries used to parse code snippets and generate code snippets, directly modifying nodes on the existing templateAST cannot meet the conversion requirements. Therefore, this application adopts a solution of traversing and analyzing the templateAST generated by the above steps to gradually generate a new jsxAST for generating new code snippets. The specific process is described as follows:

[0162] First of all, it should be made clear that template code has a major difference from script code due to its HTML language characteristics and writing restrictions in Vue: there is only one root node in AST, and the rest of the nodes are nested child nodes of the root node. Therefore, this application will use a depth-first recursive order, combined with conditional control statements, to perform different parsing processes for different types of tag nodes, in preparation for generating the final converted jsx code. The specific processing method is as follows:

[0163] If the currently traversed marked node is an ELEMENT node, since the ELEMENT node may contain attributes, instructions, events and other information, further processing is required for accurate conversion:

[0164] 1) First, take out the props attribute in the node AST, which contains a list of all attribute nodes in the ELEMENT node. For each attribute node, this application will classify and process it in combination with conditional control statements:

[0165] If the node type of the current attribute node is ATTRIBUTE (attribute), it means that it is a node attribute written in the conventional way. You only need to parse the attribute name and the corresponding attribute value from the node AST. However, due to the characteristics of the SCSS module, when processing a node attribute named style, you need to process its attribute value in a targeted manner: if the attribute value is in the global class name list obtained after the style converter analyzes it, the original attribute value is maintained unchanged; if the attribute value is in the local class name list obtained after the style converter analyzes it, the attribute value is concatenated into a new string "styles.attribute value"; for node attributes with other names, the original attribute values ​​are maintained unchanged.

[0166] If the node type of the current attribute node is DIRECTIVE (instruction), it means that it is a node attribute of instruction binding writing, such as v-if, v-else-if, v-else, v-for, v-bind, v-model, v-on, v-show, etc. For the instruction attributes such as v-if, v-else-if, v-else, v-for, and v-model, since these attributes mainly have logical capabilities, the instruction type and attribute value need to be parsed from the node AST; while for v-bind and v-on, only the real attribute name and attribute value need to be parsed from the node AST; the most special v-model instruction attribute requires special processing, because the instruction is essentially the syntax sugar of the two attribute nodes v-bind:value and v-on:input, so it is necessary to parse the attribute value from the node AST, and then construct two sets of attribute information [value (as attribute name), attribute value] and [input, attribute value assignment function (obtained by replacing the preset string template)] for subsequent node generation.

[0167] 2) After traversing the props attribute node list in the node AST, the attribute information list will be obtained. This step requires traversing the attribute information list and generating new jsxAST attribute nodes for each of its list elements:

[0168] If the current attribute information object does not contain the instruction type field, it means that the current attribute can be directly generated as the simplest jsx attribute form, which can be achieved by using jsxAttribute and jsxExpressionContainer of the @babel tool library; after generating a new jsx attribute node, this application will also filter it out of the attribute information list to facilitate the processing of subsequent steps.

[0169] If there is an instruction type field in the current attribute information object, its processing is temporarily ignored and it is retained in the attribute list for processing by the upper loop.

[0170] 3) As mentioned above, this process is a recursive process. Therefore, after processing the props attribute information of this node, take out the children attribute in the AST of this node and start recursively processing the child node list of this node. According to this process, this step will obtain the new jsxAST node and the instruction type attribute to be processed of each child node after the child node list is processed.

[0171] 4) Start to uniformly process the child nodes with instruction type attributes in the child node list. The reason for placing them in this layer is that if, else, and else-if are conditional control instructions. From the perspective of the child node processing level, the child node itself cannot perceive whether its sibling node has a paired conditional control statement. It can only be processed by the upper layer traversal from a higher perspective. First, traverse the child node list in forward order to process the for loop instruction, convert the attribute value string into a loop expression AST by calling the parseExpressionAPI, and parse the loop object and loop parameters from it, and then use the jsxExpressionCo of the @babel tool library to convert the attribute value string into a loop expression AST. ntainer cooperates with APIs such as callExpression, arrowFunctionExpression, blockStatement, etc. to construct an AST node corresponding to the code of the form "{xxx.map(y=>{return child node})}"; secondly, traverse the node list in reverse order to group the child nodes with conditional pairing relationships, such as grouping adjacent child nodes with if and else conditional control instructions, and for the child nodes contained in these groups, combine the attribute value strings parsed by each child node in the previous steps to construct the AST node corresponding to the code of the form "{a? child node 1: child node 2}".

[0172] 5) After the above steps, the attributes and child node list of the node have been successfully processed. This step will generate a new jsx node for the current node: first, take out the tag attribute in the node AST and determine whether it is the html native tag name. If not, the node is regarded as a component node and the tag name is formatted in upper camel case. If so, no processing is done; secondly, by calling the jsxElementAPI, and passing the above-processed tag name, attribute node list, child node list, etc. as parameters, a new jsx node is generated.

[0173] 6) After the above steps, the processing of the nodes at this layer has been completed. However, since this processing flow is a recursive flow, it is necessary to return the new jsx node after this processing and the instruction type attribute list to be traversed and processed by the upper layer in the form of return at the end of the process.

[0174] If the currently traversed tag node is a TEXT (text) node, since this type of node is a plain text string itself and does not need to be converted, call jsxTextAPI to generate a new jsx node for it and return it in the form of return.

[0175] If the currently traversed marked node is an INTERPOLATION node, then this node is a unique interpolation syntax in the Vue template syntax, and the processing flow is relatively simple. The interpolation content string is parsed from the node AST, and then the parseExpressionAPI is called to parse it into an expression AST, and finally the jSXExpressionContainerAPI is called to generate a new jsx node for it and then returned in the form of return.

[0176] Since the above processing flow is in the form of recursive combined with conditional control, there will be a nested and combined relationship between the processing steps. For example, when it is necessary to recursively process the child node list, the child node list may contain both INTERPOLATION nodes, TEXT nodes, and ELEMENT nodes. Therefore, the above processing flow is not always executed in the order described during actual execution. However, based on the aforementioned feature that "there is only one root node in templateAST, and the rest of the nodes are nested child nodes of the root node", after the above processing, this application will get a brand new jsx AST generated by the API of the @babel tool library.

[0177] 3. Generate a new jsx code snippet based on the new jsxAST:

[0178] Through the above steps, this application has obtained a new jsxAST. At this point, you only need to call the generatorAPI provided by the @babel tool library to generate jsx code snippets. At this point, the template code conversion is complete.

[0179] In an exemplary embodiment, step 105 may be replaced by the following steps.

[0180] Use the PostCSS tool library and the PostCSS-SCSS plug-in to parse the style code snippet and determine the styleAST; use the walkRulesAPI in the PostCSS tool library to traverse the nodes in the styleAST, and replace the ::v-deep pseudo-class in the styleAST with the :global pseudo-class to build a new styleAST; based on the new styleAST, call the processAPI provided by the PostCSS tool library to generate the converted style code snippet.

[0181] Furthermore, the walkRulesAPI in the PostCSS tool library is used to traverse the nodes in the styleAST, and the ::v-deep pseudo-class in the styleAST is replaced with the :global pseudo-class to construct a new styleAST, which specifically includes: determining whether the currently traversed node is a rule type node; if the currently traversed node is a rule type node, the processSync of the PostCSS tool library is used in conjunction with the selectorParser and walkPseudosAPI to recursively traverse the pseudo-class selectors contained in the selector field selector of the node. ; If the currently traversed node is a pseudo-class node, and the name of the pseudo-class node is the ::v-deep pseudo-class, then the pseudo-class node is used as the target pseudo-class to be processed by the converter, and selectorParser.pseudoAPI is called in conjunction with replaceWithAPI to replace the ::v-deep pseudo-class with the :global pseudo-class; if the currently traversed node is a pseudo-class node, and the name of the pseudo-class node is not the ::v-deep pseudo-class, then the pseudo-class node is ignored; if the currently traversed node is not a rule type node, then the node is ignored; until all nodes in the styleAST are traversed, a new styleAST is constructed.

[0182] Furthermore, based on the new styleAST, the processAPI provided by the PostCSS tool library is called to generate the converted style code snippet, which then includes: calling PostCSS's walkRulesAPI to traverse the rule node of the new styleAST; traversing the selectors list of the rule node, and for each list element in the selectors list, calling postcssSelectorParser to cooperate with processSyncAPI to perform secondary parsing on the list element, determining the selector list corresponding to the list element, and setting the local variable scope, initializing the local variable scope to local, and obtaining the local class name list; calling walkAPI to traverse the selector list and obtain the global class name list.

[0183] The style code converter is further described below.

[0184] Since this application supports the conversion solution of Vue(v2)+SCSS project to Vue(v2)+TSX+SCSS module project, for the style code part, both before and after the conversion are SCSS preprocessors. Therefore, unlike the previous two converters, the code conversion of the style part focuses on removing the unique syntax in the Vue file and converting it into the legal syntax in the SCSS module file. The specific steps are as follows:

[0185] 1. Parse the style code:

[0186] Use the PostCSS tool library and the PostCSS-SCSS plug-in to parse the style code - PostCSS is a powerful tool that can process and convert CSS, and the PostCSS-SCSS plug-in can parse the SCSS syntax - PostCSS's postcss and processAPI can parse the extracted SCSS style block into an abstract syntax tree (AST), which contains all the rules, selectors, and properties in the style, providing a basis for subsequent style conversion and optimization.

[0187] 2. Traverse the existing styleAST and replace the ::v-deep pseudo-class with the :global pseudo-class:

[0188] In Vue's scoped style, the ::v-deep pseudo-class is used to deeply select the style of child components, point to descendant components and apply styles. Since SCSS module files do not support features such as ::v-deep, and most ::v-deep application scenarios are to overwrite child component styles, this application will convert it to the :global pseudo-class supported by SCSS files. The specific conversion process is as follows:

[0189] First, the PostCSS tool library provides the walkRulesAPI for traversing AST nodes. This application only needs to use the traversal of this API to determine whether the currently traversed node is a rule type node. If not, ignore the node; if so, execute the subsequent steps.

[0190] If the currently traversed node is a rule type node, the processSync of the PostCSS tool library is used with the selectorParser and walkPseudos API to recursively traverse the pseudo-class selectors contained in the selector field selector of the node.

[0191] If the name of the currently traversed pseudo-class node is ::v-deep, it is the target pseudo-class to be processed by the converter. Call the selectorParser.pseudo API in conjunction with the replaceWith API to replace the pseudo-class with :global.

[0192] If the name of the currently traversed pseudo-class node is not ::v-deep, the node will be ignored.

[0193] As mentioned above, the style code conversion task is relatively simple, and the core conversion process can be seen above.

[0194] 3. Generate a new style code snippet based on the new styleAST:

[0195] Through the above steps, this application has obtained a new styleAST. At this point, we only need to call the processAPI provided by the PostCSS tool library to generate a style code snippet. At this point, the style code conversion is complete.

[0196] 4. Analyze the new style code snippet to obtain the scope of various names:

[0197] For the converter itself, the above three steps have met the conversion requirements, but for the functional completeness of the tool described in this application, the converter also needs to additionally support class name scope analysis capabilities.

[0198] SCSS module (or CSS module) is a technology that encapsulates CSS styles in modules, aiming to solve the problem of CSS global namespace and avoid style conflicts and pollution. When using SCSS module, class names are usually accessed as object properties, such as styles.xxxx. This is because after the project code is compiled and packaged, the style class names will be localized and have unique identifiers to ensure that they are only effective in specific components or modules. For example, the class name in the file will be converted into a unique identifier (), and its final usage in HTML will be <button class="styles_button__3xkj3"> ClickMe< / button> , which ensures that the class name is unique in the global scope and does not conflict with class names in other modules.

[0199] However, in some special scenarios, the use of global class names is unavoidable. The SCSS module supports the use of the special pseudo-class :global to identify such global class names, and when using them, you can just write class="button". The final usage in HTML will be <button class="button"> ClickMe< / button> .

[0200] The pre-conversion working technology stack supported by this application is Vue (v2) + SCSS. Under this technology stack, class names do not need to be accessed through object properties such as styles.xxx, and can be directly written as class="xxx".

[0201] Therefore, if the tool described in this application does not perform special processing on such class names during conversion, the class names in the converted code will all be in the form of class="xxx", which cannot be associated with the local class name, and the code will not be able to be run and used directly.

[0202] To solve this problem, this converter needs to analyze the converted new style fragment again - obtain the local class name list and the global class name list, and then judge whether to change the class name to styles.xxx or keep xxx unchanged when converting the template code:

[0203] First, get the styleAST through PostCSS's postcss.parseAPI.

[0204] Call PostCSS's walkRulesAPI to traverse the rule nodes of the AST.

[0205] Traverse the selectors list of the rule node, and for each list element, call postcssSelectorParser with processSyncAPI to perform secondary parsing on the list element to obtain the final selector list corresponding to the element, and after setting the local variable scope and initializing it to local, call walkAPI to traverse the selector list.

[0206] If the type of the currently traversed selector node is a pseudo-class, further processing is performed through conditional control statements:

[0207] If the pseudo-class name of the current node is ":global", the value of the local variable scope is modified to global; if the pseudo-class name of the current node is ":local", the value of the local variable scope is modified to local; after the above conditions are judged, determine whether the nodes field of the current pseudo-class node is a non-empty list. If it is not empty, traverse the list and store the class names involved in the list and the current scope value as key-value pairs.

[0208] If the type of the currently traversed selector node is a class, the class name and the current scope value are stored as a key-value pair.

[0209] Through the above process, this application will eventually obtain a list of {class name: scope} key-value pairs. In order to facilitate subsequent use, this step will traverse the list again and group the class names by scope value, so as to obtain the local class name list and the global class name list respectively and store them temporarily, which can be used to support the work of the template converter.

[0210] In an exemplary embodiment, step 106 may be replaced by the following steps.

[0211] Get the name of the original Vue file through the built-in API of the runtime environment; determine whether there is a "style" stage in the stage list; if so, write the converted style code snippet into the newly created xxx.module.scss file in the same directory as the original Vue file through the built-in file creation and writing API of the runtime environment; if the file writing fails, execute the next process normally, and output the warning content in the console terminal: "New SCSS module file: {xxx.module.scss} creation failed"; if the file writing is successful, output the prompt content in the console terminal: "New SCSS module file: {xxx.module.scss} creation successful", and temporarily save the SCSS module file name to the local variable; if not, skip the "style" stage; determine whether there is a "template" stage in the stage list; if not, directly skip the "template" stage, and continue to execute subsequent steps according to the converted script code snippet; if yes, determine whether there is a "script" stage in the stage list; if there is a "script" stage, call the built-in string replacement API of the runtime environment to replace the "=============jsx" set in the converted script code snippet The placeholder string here===========" is a new jsx code snippet, and the replaced script code snippet is used to continue executing subsequent steps; if the "script" stage does not exist in the stage list, a simplified version of the script code is built in, and the same "==========jsx here==========" placeholder string is used to hold the required embedded position of jsx; if both the "template" stage and the "script" stage exist in the stage list, a new TSX file is generated for the converted script code snippet; the new file name of the new TSX file is converted from the original Vue file name to lower camel case format and then concatenated with the .tsx suffix; before writing the file, determine whether the local variable of the new SCSS module file name has a value; if there is no value, it means that the conversion has not successfully generated a new SCSS module file, and a new TSX file is directly generated; if there is a value, a reference code statement "import styles is generated for the new SCSS module file from'. / xxx.module.scss';", and insert the reference code statement to the front of the script code snippet; write the script code snippet into the newly created xxx.tsx file in the same directory as the original Vue file through the built-in file creation and writing API of the runtime environment; if the file writing fails, the subsequent steps are executed normally, and the warning content is output in the console terminal: "New TSX file: {xxx.tsx} failed to be created"; if the file is written successfully, it means that this round of traversal is successfully completed, and the console terminal outputs the prompt content: "New TSX file: {xxx.tsx} created successfully", generates a new code file, and continues to execute the next round of traversal.

[0212] In summary, the overall steps of this application are as follows:

[0213] The list of legal file paths obtained in the previous steps will be taken out and traversed one by one:

[0214] a. Read the file content according to the file path and pass it to the parseComponentAPI of the vue-template-compiler tool library for parsing. As mentioned in the previous content, a regular Vue file consists of three parts: template, script, and style. The function of parseComponentAPI is to parse the code snippets of these three parts from the file content, namely, template code snippet, script code snippet, and style code snippet; similarly, as mentioned in the previous content, these three parts are actually written in three different programming languages ​​and cannot be processed uniformly. This application will also convert these three parts separately in the future.

[0215] b. Take out the stage list obtained in the previous step. If the "style" stage does not exist in the list, or the style code snippet is an empty string, skip this step directly; otherwise, convert the style code snippet normally.

[0216] c. Take out the stage list obtained in the previous step. If the "script" stage does not exist in the list, or the script code snippet is an empty string, skip this step directly; otherwise, convert the script code snippet normally.

[0217] d. Take out the stage list obtained in the previous step. If the "template" stage does not exist in the list, or the template code snippet is an empty string, skip this step directly; otherwise, convert the template code snippet normally.

[0218] e. After completing steps b, c, and d respectively, you will get at least one of the new template code snippet (that is, the jsx code snippet), script code snippet, and style code snippet. In this step, you need to combine these three new code snippets and generate a new code file:

[0219] First, the names of the newly generated code files are based on the names of the original files, so here we first obtain the original file names through the built-in API of the runtime environment.

[0220] Take out the stage list obtained in the previous step. If the "style" stage does not exist in the list, skip this step directly; otherwise, directly generate a new SCSS module file for the style code snippet. The new file name is converted from the original file name to kebab-case format (referring to the format formed by connecting pure lowercase English words with hyphens) and then concatenated with the .module.scss suffix, such as "abc.module.scss". This step will write the new style code snippet into the newly created xxx.module.scss file in the same directory as the original file through the built-in file creation and writing API of the runtime environment. If the file writing fails, the application will execute the subsequent steps normally and output the warning content in the console terminal: "New SCSSmodule file: {xxx.module.scss} failed to be created"; if the file is written successfully, the prompt content is output in the console terminal: "New SCSS module file: {xxx.module.scss} successfully created", and the SCSS module file name is temporarily stored in the local variable before continuing to execute the subsequent steps.

[0221] Take out the stage list obtained in the previous step. If the "template" stage does not exist in the list, skip this step directly and use the converted script code snippet obtained in the previous step to continue to execute the subsequent steps; otherwise, determine whether there is a "script" stage in the list. If the "script" stage exists in the list, it is necessary to call the built-in string replacement API of the runtime environment to replace the specially set "===========jsx here==========" placeholder string in the new script code snippet with the new jsx code snippet, and use the replaced script code snippet to continue to execute the subsequent steps; if the "script" stage does not exist in the list, in view of the fact that the jsx code in the TSX file needs to be embedded in the script code, this application will build in a simplified version of the script code, and use the same "===========jsx here==========" placeholder string to hold the required embedded position of jsx, and in this step, as a fallback solution for the absence of a "script" stage, it is used for embedded use after the new jsx code snippet replaces the placeholder string, and the replaced built-in script code snippet is used to continue to execute the subsequent steps.

[0222] Take out the stage list obtained in the previous step. If there is neither the "template" stage nor the "script" stage in the list, skip this step directly; otherwise, generate a new TSX file for the script code snippet processed in the previous step. The new file name is formed by converting the original file name into camel case format and concatenating the .tsx suffix, such as "helloWorld.tsx". Before writing the file, it is also necessary to determine whether the SCSS module file name local variable has a value. If there is no value, it means that the conversion has not successfully generated a new SCSS module file, and a new TSX file can be generated directly; if it exists, it is necessary to generate a reference code statement "import styles from'. / xxx.module.scss';" for the SCSS module file generated above, and insert the statement at the front of the script code. Then, the script code is written to the newly created xxx.tsx file in the same directory as the original file through the built-in file creation and writing API of the runtime environment. If the file writing fails, this application will execute the subsequent steps normally and output a warning in the console terminal: "New TSX file: {xxx.tsx} creation failed"; if the file writing is successful, it means that this round of traversal is successfully completed, and the prompt content is output in the console terminal: "New TSX file: {xxx.tsx} creation successful", and continue to the next round of traversal.

[0223] After successfully completing the code conversion process, the command line tool described in this application will output the conversion success information in the command line terminal, and then call the built-in API exit script of the operating environment and return the corresponding exit code (usually 0, indicating success).

[0224] The command line interface-based front-end code automatic conversion method provided in this application can efficiently and accurately convert Vue files into TSX files and their corresponding dependent SCSS module files.

[0225] By comprehensively utilizing libraries such as @babel, @vue / compiler-dom, postcss, postcss-scss, postcss-selector-parser, and sass, this application has achieved a number of innovations and optimizations in the technical solution, bringing the following beneficial effects:

[0226] 1) Efficient file parsing and conversion:

[0227] Automated processing: This application uses command line tools to achieve automatic parsing and conversion of Vue files, reducing manual intervention and improving conversion efficiency.

[0228] Parsing accuracy: With the help of tools such as @vue / compiler-dom and TypeScript, this application can accurately parse the template, script, and style parts of the Vue file and generate a high-precision abstract syntax tree (AST) representation, providing a solid foundation for subsequent conversion.

[0229] Efficient conversion: By converting the Vue code represented by AST into JSX, TypeScript, and SCSS code that meets the requirements of TSX files, this application implements an efficient code conversion process to ensure the consistency of the converted code in function, logic, and style.

[0230] 2) Support SCSS style blocks and deep selectors:

[0231] SCSS support: This application can process SCSS style blocks in Vue files, retaining and converting variables, nested rules, mixins and other features, ensuring that the styles can be correctly applied in the converted environment.

[0232] Deep selector processing: This application can recognize and process the ::v-deep pseudo-class allowed in Vue files and convert it to the :global pseudo-class supported by SCSS files, thereby maintaining the scope and deep selector characteristics of the style and ensuring that the style is correctly applied in the converted TSX file.

[0233] 3) Simple and easy-to-use command line tools:

[0234] This application provides a concise and easy-to-use command line tool. Users can quickly perform Vue file conversions through simple commands and parameter configurations. The tool supports a variety of configuration options, such as file path, conversion process customization, etc., to flexibly adapt to the needs of different projects.

[0235] 4) Improve development efficiency and project quality:

[0236] Seamless conversion of Vue files to TSX files is achieved through automated tools, which greatly reduces the workload and time cost of manual conversion and significantly improves development efficiency.

[0237] In summary, this application realizes the efficient conversion of Vue files to TSX files through automated tools, which brings significant beneficial effects, including efficient file parsing and conversion, powerful code optimization, concise and easy-to-use command line tools and other features. It provides developers with a powerful and flexible tool to help them smoothly migrate existing Vue projects to projects using TypeScript and TSX syntax, thereby improving the overall quality of the project and development experience.

[0238] The automated conversion tool for this application is suitable for the following technology stacks and project types:

[0239] Vue(v2) Single File Component (SFC).

[0240] Projects that use SCSS as a style preprocessor.

[0241] Projects that need to convert Vue files to TypeScript and TSX files.

[0242] In an exemplary embodiment, the present application also provides a computer device, including: a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor executes the computer program to implement the above-mentioned command line interface-based front-end code automatic conversion method.

[0243] In an exemplary embodiment, the present application also provides a computer-readable storage medium having a computer program stored thereon, and when the computer program is executed by a processor, the above-mentioned command line interface-based front-end code automatic conversion method is implemented.

[0244] In an exemplary embodiment, the present application also provides a computer program product, including a computer program, which implements the above-mentioned command line interface-based front-end code automatic conversion method when executed by a processor.

[0245] This article uses specific examples to illustrate the principles and implementation methods of this application. The description of the above embodiments is only used to help understand the method and core ideas of this application. At the same time, for those skilled in the art, according to the ideas of this application, there will be changes in the specific implementation methods and application scope. In summary, the content of this specification should not be understood as limiting this application.

Claims

1. A method for automatic conversion of front-end codes based on a command line interface, characterized in that: The method for automatically converting front-end code based on a command line interface includes: Enter v2j in the command line interface to start the command line tool; the basic instructions of the command line tool include the path instruction of the specified configuration file, the path instruction of the file to be processed, and the stage instruction to be processed; the stages to be processed include the "style" stage, the "template" stage, and the "script" stage; Based on the command line tool, according to the command line parameters input by the user, the parseComponent API is used to parse the script code snippet, template code snippet and style code snippet in the Vue file; Based on the TypeScript class component of the TypeScript tool library, using a script code converter to perform code conversion on the script code fragment to generate a converted script code fragment; Based on the @vue / compiler-dom tool library and the @babel tool library, the template code snippet is converted by using the template code converter to generate a converted template code snippet; Based on the PostCSS tool library and the PostCSS-SCSS plug-in, the style code fragment is converted by using a style code converter to generate a converted style code fragment; the style code converter is a SCSS preprocessor; The converted template code snippet and the converted style code snippet are combined and processed, and the combined code snippet and the converted script code snippet are converted into a new code file; the new code file includes a TSX file and a SCSS module file, wherein the TSX file is used to store the converted script code snippet and template code snippet, and the SCSS module file is used to store the converted style code snippet; the command line parameters include a configuration file path parameter, a to-be-converted file path list parameter, and a code conversion necessary processing stage parameter.

2. The method for automatic front-end code conversion based on command line interface according to claim 1, characterized in that: Based on the command line tool, according to the command line parameters input by the user, the parseComponent API is used to parse the script code snippets, template code snippets and style code snippets in the Vue file, which also includes: the configuration file path parameter verification process, the file path list parameter verification process to be converted and the code conversion must be processed. The configuration file path parameter verification process is as follows: Verify the configuration file path parameter. If the user does not specify the configuration file path parameter, read the USER_DEFINED_CONFIG_PATH variable configured by the user in the running environment, and use the USER_DEFINED_CONFIG_PATH variable as the configuration file path; Verify whether the configuration file path really exists, and call the built-in import method of the runtime environment to load and read the configuration file path; If the configuration file path does not exist, the file content reading fails, or the file content is empty, the process is terminated and different error messages are output in the terminal: "Configuration file not found", "Configuration file content reading failed", or "Configuration file content is empty"; If the configuration file path exists and the configuration content in the configuration file path file is read successfully, the read configuration content is temporarily stored in the global variable to complete the configuration file path parameter verification process; If the user does not specify the configuration file path parameter in the command line or configure the USER_DEFINED_CONFIG_PATH environment variable in the runtime environment, the built-in file creation API and file writing API of the code runtime environment are automatically called in the current working directory of the user's command line execution to generate a configuration file named "vue-sfc-to-jsx.config.ts". The content of the configuration file is a built-in default configuration code. If the configuration file is written successfully, repeat the configuration file path parameter verification process; If the configuration file fails to be written, the process is terminated and an error message "Configuration file writing failed" is output in the terminal; The parameter verification process of the file path list to be converted is as follows: If the user does not specify the file path list parameter to be converted, the process is terminated directly and an error message "No file to be processed is specified" is output in the terminal; If the user specifies the file path list parameter to be converted, the parameter value of the string type is cut through the built-in API of the operating environment, and the cutting point is the English half-width comma, and a file path list is obtained; Traverse the file path list, process the leading and trailing spaces of the file path string one by one, and verify whether the processed file path is a legal Vue file path; If no legal Vue file path is found after verification, the process is terminated directly and an error message "No legal Vue file path specified" is output in the terminal; If there are both legal Vue file paths and illegal Vue file paths, continue to execute the next process and output a warning message in the terminal "There is an illegal path: {path A}|{path B}|..."; If all are legal Vue file paths, continue to execute the next process normally; Temporarily store the list of file paths to be converted that have been verified as legal into a global variable; The parameter verification process of the code conversion must be processed as follows: If the user does not specify the code conversion must process the phase parameters, directly skip the code conversion must process the phase parameter verification process, and in the subsequent conversion process, perform full-stage conversion, and temporarily store the full-stage list ["style", "script", "template"] into a global variable; If the user specifies the code conversion must process the stage parameter, the parameter value of the string type is cut through the built-in API of the runtime environment, the cutting point is the English half-width comma, and a stage list is obtained; Traverse the stage list, process the leading and trailing spaces of the stage string one by one, and verify whether the processed stage is a legal stage; the legal stages include ["style", "script", "template"]; "style" is the "style" stage, "template" is the "template" stage, and "script" is the "script" stage; If no legal stage is found after processing and verification, the process is terminated directly and an error message "No legal stage specified" is output on the terminal; If there are both legal and illegal stages, continue to execute the next process and output a warning message in the terminal "Illegal stage will be ignored: {path A}|{path B}|..."; If all are legal stages, continue to execute the next process normally; Temporarily store the stage list that has been verified to be legal in a global variable.

3. The method for automatic front-end code conversion based on command line interface according to claim 1, characterized in that: Based on the TypeScript class component of the TypeScript tool library, the script code snippet is converted by using a script code converter to generate a converted script code snippet, specifically including: Use the createSourceFileAPI in the TypeScript class component of the TypeScript tool library to parse the script code snippet and determine the scriptAST; the scriptAST includes all syntax nodes in the Vue file, and the syntax nodes include data, methods, calculated properties, and lifecycle hooks; Use the transform method in the TypeScript class component of the TypeScript tool library to traverse each syntax node in the scriptAST in a breadth-first traversal order to determine the type of each syntax node; Parse different types of syntax nodes and build a new scriptAST; Based on the new scriptAST, the printFileAPI in the TypeScript tool library is called to generate a converted script code snippet.

4. The method for automatic front-end code conversion based on command line interface according to claim 3 is characterized in that: Parse different types of syntax nodes and build a new scriptAST, including: If the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of the PropertyAssignment node is "name", the node initialization value corresponding to the PropertyAssignment node is taken out and temporarily stored as the component name of the subsequent new jsx code snippet; If the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of the PropertyAssignment node is "data", and the initialization value node of the PropertyAssignment node is a method node, parse out the PropertyAssignment node corresponding to the return statement of the method node, and recursively traverse the PropertyAssignment node to parse out the first object property-value pair list; Call the typescript createPropertyDeclaration API to generate a new first-class attribute node for each element in the first object's attribute-value pair list as part of the subsequent new jsxAST; If the currently traversed syntax node is a MethodDeclaration node, and the name identifier string of the MethodDeclaration node is "data", parse out the MethodDeclaration node corresponding to the return statement of the MethodDeclaration node, and recursively traverse the MethodDeclaration node to parse out the second object attribute-value pair list; Call the typescript createPropertyDeclaration API to generate a new second-class attribute node for each element in the second object's attribute-value pair list as part of the subsequent new jsxAST; If the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of the PropertyAssignment node is one of "components", "filters" or "directives", then the PropertyAssignment node is temporarily stored for subsequent reuse to form part of the new jsxAST; If the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of the PropertyAssignment node is "computed", and the initialization value node of the PropertyAssignment node is an object type node, then recursively traverse the object AST nodes to parse out the property name, property calculation method, and property accessor type corresponding to each computed property; Call the createGetAccessorDeclaration method or the createSetAccessorDeclaration method to generate a new class accessor attribute node corresponding to the calculated attribute as part of the subsequent new jsxAST; If the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of the PropertyAssignment node is "methods", and the initialization value node of the PropertyAssignment node is an object type node, then recursively traverse the object AST node to parse out the method name, method input parameter, function body and modifiers corresponding to each component method; Call the createMethodDeclaration method to generate a new class method node corresponding to the component method as part of the subsequent new jsxAST; If the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of the PropertyAssignment node is "props", and the initialization value node of the PropertyAssignment node is an object type node, then recursively traverse the object AST node to parse out the prop identifier name and prop initialization value corresponding to each component prop; Call the createPropertyDeclaration method to generate a new first-class property declaration node corresponding to the component prop as part of the subsequent new jsxAST; If the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of the PropertyAssignment node is "props", and the initialization value node of the PropertyAssignment node is an array type node, then traverse the array AST nodes, and call the createPropertyDeclaration method for the array elements to generate a new second-class property declaration node corresponding to the component prop as part of the subsequent new jsxAST; If the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of the PropertyAssignment node is "watch", and the initialization value node of the PropertyAssignment node is an object type node, then recursively traverse the object AST node to parse out the watcher identifier name, watcher method parameters, watcher method body, watcher object, and watcher configuration corresponding to each component watcher; Call the createMethodDeclaration method to generate a new class method declaration node corresponding to the component watcher as part of the subsequent new jsxAST; If the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of the PropertyAssignment node is any of "beforeCreate", "created", "beforeMount", "mounted", "beforeUpdate", "updated", "activated", "deactivated", "beforeDestroy", "destroyed" and "errorCaptured", then the current node is a Vue component lifecycle hook node, and the identifier name, method parameters, method body and identifier corresponding to the lifecycle method are parsed from the Vue component lifecycle hook node; Call the createMethodDeclaration method to generate a new class method declaration node corresponding to the Vue component lifecycle hook node as part of the subsequent new jsxAST; If the currently traversed syntax node is an ExportAssignment node, it means that the current node is a default export node, and a comprehensive recursive traversal is performed on the expression child nodes of the default export node, and the processing of the default export node is skipped; If the currently traversed syntax node is an unprocessed node, there is no need to recursively traverse it, and the unprocessed node is only temporarily stored and reserved for later use as part of the new jsxAST; the unprocessed node is an ImportDeclaration node, an ExportDeclaration node, or a VariableStatement node; Build a new script AST based on the component name of the new jsx code snippet and part of said new jsxAST.

5. The method for automatic front-end code conversion based on command line interface according to claim 1, characterized in that: Based on the @vue / compiler-dom tool library and the @babel tool library, the template code snippet is converted using the template code converter to generate the converted template code snippet, specifically including: Use the parseAPI of the @vue / compiler-dom tool library to parse the template code snippet to obtain templateAST; the templateAST includes all types of nodes in the component template; the types of nodes include label nodes, text nodes, instruction nodes, and component nodes; Traverse the templateAST, use depth-first recursive order, combine conditional control statements, perform different parsing processes on different types of tag nodes, and build a new jsxAST based on the API of the @babel tool library; Based on the new jsxAST, the generatorAPI in the @babel tool library is called to generate a jsx code snippet; the jsx code snippet is a converted template code snippet.

6. The method for automatic front-end code conversion based on command line interface according to claim 5, characterized in that: Traverse the templateAST, use depth-first recursive order, combine conditional control statements, perform different parsing processes on different types of tag nodes, and build a new jsxAST based on the API of the @babel tool library, including: If the currently traversed marked node is an ELEMENT node, determine the props attribute in the ELEMENT node; the props attribute includes a list of all attribute nodes in the ELEMENT node; Classify each attribute node in the attribute node list in combination with the conditional control statement to determine an attribute information list; Traverse the attribute information list and generate a new jsx AST attribute node corresponding to each element in the attribute information list; If the currently traversed marked node is an ELEMENT node, determine the children attribute in the ELEMENT node, recursively process the child node list of the ELEMENT node, and determine the new jsxAST node and the instruction type attribute to be processed for each child node; Traverse the child node list in positive order to process the for loop instruction, call parseExpressionAPI to convert the attribute value string into a loop expression AST, and parse the loop object and loop parameter therefrom, and then construct an AST node corresponding to the code of the form "{xxx.map(y=>{return child node})}" by using jsxExpressionContainer of @babel tool library in conjunction with multiple APIs; the multiple APIs include callExpression, arrowFunctionExpression and blockStatement; among which, xxx.map is a loop statement and y is a loop parameter; Traverse the sub-node list in reverse order, group the sub-nodes with conditional pairing relationships, and construct AST nodes corresponding to codes in the form of "{a? sub-node 1: sub-node 2}" in combination with the attribute value strings of each sub-node for the sub-nodes included in these groups; wherein "{a? sub-node 1: sub-node 2}" is a conditional control code block; a is the judgment condition in the conditional control statement; Take out the tag attribute in the node AST and determine whether the tag attribute is the html native tag name; if so, do nothing; if not, treat the ELEMENT node as a component node and format the name of the tag attribute in upper camel case; Call jsxElementAPI, pass the processed tag attribute name, processed attribute node list and processed child node list as parameters to generate a new jsx node; If the currently traversed marked node is a TEXT node, call jsxTextAPI to generate a new jsx node for the TEXT node; If the currently traversed marked node is an INTERPOLATION node, parse the interpolation content string from the node AST, then call parseExpressionAPI to parse the INTERPOLATION node into an expression AST, and finally call jSXExpressionContainerAPI to generate a new jsx node for the INTERPOLATION node; Based on the API of the @babel tool library, a new jsxAST is built based on all new jsx nodes.

7. The method for automatic front-end code conversion based on command line interface according to claim 1, characterized in that: Based on the PostCSS tool library and the PostCSS-SCSS plug-in, using the style code converter to convert the style code fragment to generate a converted style code fragment; The style code converter is a SCSS preprocessor, which specifically includes: Use the PostCSS tool library and PostCSS-SCSS plugin to parse the style code snippet and determine the styleAST; Use the walkRulesAPI in the PostCSS tool library to traverse the nodes in the styleAST, and replace the ::v-deep pseudo-class in the styleAST with the :global pseudo-class to build a new styleAST; Based on the new styleAST, the processAPI provided by the PostCSS tool library is called to generate the converted style code snippet.

8. The method for automatic front-end code conversion based on command line interface according to claim 1, characterized in that: Use the walkRulesAPI in the PostCSS tool library to traverse the nodes in the styleAST, and replace the ::v-deep pseudo-class in the styleAST with the :global pseudo-class to build a new styleAST, including: Determine whether the currently traversed node is a rule type node; If the currently traversed node is a rule type node, use processSync of the PostCSS tool library with selectorParser and walkPseudosAPI to recursively traverse the pseudo-class selectors contained in the selector field selector of the node; if the currently traversed node is a pseudo-class node, and the name of the pseudo-class node is the ::v-deep pseudo-class, then the pseudo-class node is used as the target pseudo-class to be processed by the converter, and call selectorParser.pseudoAPI with replaceWithAPI to replace the ::v-deep pseudo-class with the :global pseudo-class; if the currently traversed node is a pseudo-class node, and the name of the pseudo-class node is not the ::v-deep pseudo-class, then ignore the pseudo-class node; If the currently traversed node is not a rule type node, the node will be ignored; Until all nodes in the styleAST are traversed, a new styleAST is constructed.

9. The method for automatic front-end code conversion based on command line interface according to claim 8, characterized in that: Based on the new styleAST, the processAPI provided by the PostCSS tool library is called to generate the converted style code snippet, which also includes: Call PostCSS's walkRulesAPI to traverse the rule nodes of the new styleAST; Traverse the selectors list of the rule node, and for each list element in the selectors list, call postcssSelectorParser with processSyncAPI to perform secondary parsing on the list element, determine the selector list corresponding to the list element, set the local variable scope, initialize the local variable scope to local, and obtain the local class name list; Call walkAPI to traverse the selector list and obtain the global class name list.

10. The method for automatic front-end code conversion based on command line interface according to claim 2, characterized in that: The converted template code snippet and the converted style code snippet are combined and processed, and the combined code snippet and the converted script code snippet are converted into a new code file, specifically including: Get the original Vue file name through the built-in API of the running environment; Determine whether there is a "style" stage in the stage list; if so, write the converted style code snippet into the newly created xxx.module.scss file in the same directory as the original Vue file through the built-in file creation and writing API of the runtime environment; if the file writing fails, execute the next process normally, and output the warning content in the console terminal: "New SCSSmodule file: {xxx.module.scss} creation failed"; if the file writing is successful, output the prompt content in the console terminal: "New SCSS module file: {xxx.module.scss} creation successful", and temporarily save the SCSS module file name to the local variable; if not, skip the "style" stage; Determine whether there is a "template" stage in the stage list; if not, directly skip the "template" stage, and continue to execute subsequent steps according to the converted script code snippet; if yes, determine whether there is a "script" stage in the stage list; if there is a "script" stage, call the built-in string replacement API of the running environment to replace the "===========jsx here===========" placeholder string set in the converted script code snippet with a new jsx code snippet, and continue to execute subsequent steps using the replaced script code snippet; if there is no "script" stage in the stage list, embed a simplified version of the script code, and use the same "===========jsx here===========" placeholder string to hold the required embedded position of jsx; If there is both a "template" stage and a "script" stage in the stage list, a new TSX file is generated for the converted script code snippet; the new file name of the new TSX file is converted from the original Vue file name to lower camel case format and then concatenated with the .tsx suffix; Before writing the file, determine whether the local variable of the new SCSS module file name has a value; if there is no value, it means that the conversion has not successfully generated a new SCSS module file, and a new TSX file is directly generated; if there is a value, generate a reference code statement "import styles from'. / xxx.module.scss';" for the new SCSSmodule file, and insert the reference code statement to the front of the script code snippet; The script code snippet is written into the newly created xxx.tsx file in the same directory as the original Vue file through the built-in file creation and writing API in the running environment; if the file writing fails, the subsequent steps are executed normally, and a warning content is output in the console terminal: "New TSX file: {xxx.tsx} creation failed"; if the file is written successfully, it indicates that this round of traversal is successfully completed, and the prompt content is output in the console terminal: "New TSX file: {xxx.tsx} creation is successful", a new code file is generated, and the next round of traversal continues.

11. A computer device comprising: A memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor executes the computer program to implement the command line interface-based front-end code automatic conversion method described in any one of claims 1 to 10.

12. A computer-readable storage medium having a computer program stored thereon, characterized in that: When the computer program is executed by a processor, the method for automatic front-end code conversion based on a command line interface described in any one of claims 1 to 10 is implemented.

13. A computer program product, comprising a computer program, characterized in that When the computer program is executed by a processor, the method for automatic front-end code conversion based on a command line interface described in any one of claims 1 to 10 is implemented.

Citation Information

Patent Citations

  • Vue file conversion method and device, electronic equipment and storage medium

    CN113360141A

  • Method and device for constructing front-end code engineering based on low-code application

    CN115857926A

  • Code conversion method, system and device between different front-end frames

    CN115951890A

  • Front-end frame assembly automatic conversion method and system, electronic equipment and storage medium

    CN118245050A

  • Systems and methods for generic data parsing applications

    US12001416B1