Method, Device, Medium and Product for Automatically Converting Front-End Code Based on Command-Line Interface
The script, template and style code snippets of Vue files are parsed and converted through command line tools, and the problem of manual conversion of Vue files is solved. It realizes efficient and accurate automatic conversion, and improves the maintainability and readability of the code.
Patent Information
- Application Number
- CN202411730390.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2024-11-29
- Publication Date
- 2025-07-22
- Estimated Expiration
- 2044-11-29
AI Technical Summary
Manually converting Vue files to TypeScript JSX files (TSX files) is inefficient and error-prone, especially in large projects, requiring developers to have dual skills and handle complex type definitions and component conversion details.
It provides a front-end code automatic conversion method based on the command line interface. It parses script, template and style code snippets in Vue files through command line tools, and uses the TypeScript tool library, @vue/compiler-dom tool library, @babel tool library and PostCSS tool library to convert them separately to generate TSX files and SCSS module files.
Improves the conversion efficiency of Vue files to TSX files, reduces the probability of errors, and enhances the maintainability and readability of the converted code.
Smart Images

Figure CN119668625B_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of automatic front - end code conversion, and particularly 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 technologies, Vue.js, as a progressive JavaScript framework, has been widely used in front - end development. Due to its ease of use, high flexibility and strong community support, Vue.js has become an ideal choice for developing single - page applications (SPAs). However, with the expansion of project scale and the increase in complexity, 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 better support for development tools. It can not only effectively improve code maintainability but also greatly enhance the development efficiency of R & D engineers. Therefore, it is gradually widely used in large - scale projects.
[0004] In this context, JSX and TSX, as important tools for front - end development, have gradually attracted the attention and use of developers.
[0005] JSX (JavaScript XML) is a syntax extension of JavaScript, usually used in React development. JSX allows developers to write XML - like code in JavaScript, thus constructing user interfaces more intuitively. 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 supporting the static type - checking of TypeScript. TSX files usually have the suffix.tsx, 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 both the intuitiveness of the code and improving the security and maintainability of the code.
[0007] In actual front - end development work, more and more projects are gradually migrating from a 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 catch type errors at the compilation stage, reduce runtime errors, and improve the reliability and maintainability of the code.
[0009] Development tool support: TypeScript has rich development tool support, including intelligent code hints, code completion, refactoring tools, etc., which helps improve development efficiency and code quality.
[0010] Code quality and maintainability: TypeScript's strong type system makes the code more self-documenting, facilitating teamwork and code maintenance, especially in large projects.
[0011] Community and ecosystem: With the popularity of TypeScript, more and more open-source libraries and projects start to support or give priority to TypeScript. Using TSX files helps make better use of these resources.
[0012] However, manually converting a large number of Vue files (.vue) to TypeScriptJSX files (.tsx) is a cumbersome 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 occur during the conversion process, such as type definitions, transformation of component properties, and lifecycle methods. If not handled properly, it is easy to introduce new errors and cause the project to malfunction. In addition, manually converting a large number of files consumes a lot of time and effort, reducing development efficiency. Summary of the Invention
[0013] The purpose of this application is to provide a method, device, medium, and product for automatically converting front-end code based on a command-line interface to solve the problems of low development efficiency and easy errors in manual file conversion.
[0014] To achieve the above purpose, this application provides the following solutions:
[0015] In the first aspect, this application provides a method for automatically converting front-end code based on a command-line interface, including:
[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 for specifying the configuration file, the path instruction for specifying the file to be processed, and the instruction for specifying the stage to be processed; among them, 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, use the parseComponent API to parse out the script code snippet, template code snippet, and style code snippet in the Vue file;
[0018] For a TypeScript class component based on the TypeScript tool library, use a script code converter to perform code conversion on the script code snippet to generate a converted script code snippet;
[0019] Based on the @vue / compiler-dom tool library and the @babel tool library, use a template code converter to perform code conversion on the template code snippet to generate a converted template code snippet;
[0020] Based on the PostCSS tool library and the PostCSS-SCSS plugin, use a style code converter to perform code conversion on the style code snippet to generate a converted style code snippet; the style code converter is an SCSS preprocessor;
[0021] Fuse the converted template code snippet and the converted style code snippet, and convert the fused code snippet and the converted script code snippet into a new code file; the new code file includes a TSX file and an SCSS module file, where 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 list of paths of files to be converted, and a parameter for the necessary processing stage of code conversion.
[0022] In a second aspect, the present application provides a computer device, including: a memory, a processor, and a computer program stored on the memory and executable on the processor, where the processor executes the computer program to implement the front-end code automatic conversion method based on a command-line interface described in any one of the above.
[0023] In a third aspect, the present application provides a computer-readable storage medium, on which a computer program is stored, and when the computer program is executed by a processor, it implements the front-end code automatic conversion method based on a command-line interface described in any one of the above.
[0024] Fourthly, the present application provides a computer program product, including a computer program which, when executed by a processor, implements the method for automatically converting front-end code based on a command-line interface described in any one of the above.
[0025] According to the specific embodiments provided by the present application, the following technical effects are disclosed: In order to improve the code migration efficiency and code quality, the present application starts a command-line tool through the command-line interface, and based on this command-line tool, according to the command-line parameters input by the user, uses the parseComponentAPI to parse out the script code snippet, template code snippet, and style code snippet in the Vue file; and through the TypeScript tool library, @vue / compiler-dom tool library, @babel tool library, as well as the PostCSS tool library and PostCSS-SCSS plugin, respectively convert the script code snippet, template code snippet, and style code snippet. Finally, the converted script code snippet, converted template code snippet, and converted style code snippet are combined to generate a new code file; this new code file is the TSX file and SCSS module file. The present application can automatically convert the Vue file into a TSX file in stages by simply executing a command (i.e., the command-line parameters input by the user) through the command-line tool, improving the development efficiency of the conversion file and reducing the probability of conversion errors. BRIEF DESCRIPTION OF THE DRAWINGS
[0026] In order to more clearly illustrate the technical solutions in the embodiments of the present application or the prior art, the following will briefly introduce the drawings required in the embodiments. Obviously, the drawings described below are only some embodiments of the present application. For those of ordinary skill in the art, without creative efforts, other drawings can also be obtained based on these drawings.
[0027] Figure 1 It is a flowchart of a method for automatically converting front-end code based on a command-line interface in an embodiment of the present application. DETAILED DESCRIPTION OF THE EMBODIMENTS
[0028] The following will clearly and completely describe the technical solutions in the embodiments of the present application with reference to the drawings in the embodiments of the present application. Obviously, the described embodiments are only some embodiments of the present application, rather than all embodiments. Based on the embodiments in the present application, all other embodiments obtained by those of ordinary skill in the art without creative efforts belong to the scope of protection of the present application.
[0029] To make the above objects, features, and advantages of the present application more apparent and understandable, the present application will be further described in detail below with reference to the accompanying drawings and specific embodiments.
[0030] Currently, there are some tools and libraries in the market that can assist developers in using TypeScript in Vue projects. For example, the Vue official provides the Vue CLI tool, which supports creating and managing Vue + TS projects; there are also some community-contributed tools that can help developers gradually introduce TypeScript in Vue projects. However, these tools mainly provide support for new projects or gradually introduce TypeScript in existing projects, rather than being specifically used for the automatic conversion of Vue files to TSX files.
[0031] The following are some existing solutions known to the inventors:
[0032] Vue CLI: Vue CLI is a powerful scaffolding tool provided by the Vue official, which supports creating 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 into TSX files.
[0033] Community tools: Some community-contributed tools and plugins can help developers introduce TypeScript in 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 mainly assist in writing and managing TypeScript code, rather than automatically converting existing Vue files.
[0034] In summary, for the need of automatically converting Vue files to TSX files, there is currently no mature and widely used tool. Therefore, the existing solutions mainly rely on manual conversion or are implemented by writing custom scripts, which have problems such as high development cost, low efficiency, and easy errors.
[0035] The front-end code automatic conversion method based on the command-line interface provided by the embodiments of the present application is executed by a computer device. Specifically, it can be executed alone by a computer device such as a terminal or a server, or jointly executed by a terminal and a server. 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 the path instruction for specifying the configuration file, the path instruction for specifying the file to be processed, and the stage instruction for specifying the stage to be processed; among them, 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, use the parseComponentAPI to parse out the script code snippet, the template code snippet, and the style code snippet in the Vue file.
[0038] Step 103: Based on the TypeScript class component of the TypeScript tool library, use the script code converter to perform code conversion on the script code snippet to generate the converted script code snippet.
[0039] Step 104: Based on the @vue / compiler-dom tool library and the @babel tool library, use the template code converter to perform code conversion on the template code snippet to generate the converted template code snippet.
[0040] Step 105: Based on the PostCSS tool library and the PostCSS-SCSS plugin, use the style code converter to perform code conversion on the style code snippet to generate the converted style code snippet; the style code converter is an SCSS preprocessor.
[0041] Step 106: Blend and process 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 an SCSS module file, where the TSX file is used to store the converted script code snippet and the template code snippet, and the SCSS module file is used to store the converted style code snippet; the command line parameters include the configuration file path parameter, the list parameter of the file paths to be converted, and the required processing stage parameter for code conversion.
[0042] Since the template, script, and style parts of the Vue file each have unique syntax and structures, different conversion strategies are required to achieve an accurate conversion to a TSX file. The unique syntax and structures of the three parts are as follows:
[0043] 1. Syntax 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 Vue components in the TSX environment.
[0046] The style part needs to be converted from Vue's scoped styles to CSS Modules.
[0047] 2. Conversion complexity:
[0048] The conversion of each part involves different syntax parsers and conversion rules. Handling them separately can reduce the overall conversion complexity.
[0049] 3. Error isolation:
[0050] Handling them separately can more easily locate and handle conversion errors that may occur in each part without affecting each other.
[0051] 4. Modular processing:
[0052] Handling them separately is conducive to implementing a modular conversion process, facilitating subsequent maintenance and upgrading of each conversion module.
[0053] 5. Performance optimization:
[0054] Handling them separately allows the conversion process to be executed in parallel, improving the conversion efficiency.
[0055] By handling 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 method not only improves the accuracy and efficiency of the conversion but also enhances the maintainability and readability of the converted code.
[0056] To facilitate developers' use, this application designs a simple and easy-to-use command-line tool for converting Vue files into TSX files. This 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 simple and clear tool name: v2j. Users can start the conversion tool by entering this name in the command line. To parse the commands and parameters entered by the user and dispatch the corresponding code processing logic, this application creates a core entry file (cli.js), which will be responsible for the above core interaction functions.
[0058] Basic commands: This application defines the basic commands of the tool for triggering file conversion:
[0059] v2j - f{vue filepath} - c{config filepath} - s{stages, conversions to be performed}
[0060] Among them, - f is a required parameter used to specify the Vue file 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, representing 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 to be converted
[0066] This is a required parameter used to specify the specific 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 conversion stages to be performed
[0073] In this command structure, the Vue file path following `- f` is the only required parameter, and its official name is "Input File Path Parameter". The 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 of the configuration file
[0076] -f, --files: Specify the paths of the files to be processed, separated by English half-width commas for multiple files
[0077] -s, --stages: Specify the stages to be processed. A total of three stages are supported: template, style, and script, separated by English half-width 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ˋ (configuration full name)
[0082] Function: Specify the path of the configuration file
[0083] 2. File path parameters:
[0084] Short format: ˋ-fˋ (file abbreviation)
[0085] Long format: ˋ--filesˋ (file full name)
[0086] Function: Specify the paths of the files to be processed, separated by English half-width commas for multiple files
[0087] 3. Processing stage parameters:
[0088] Short format: ˋ-sˋ (stage abbreviation)
[0089] Long format: ˋ--stagesˋ (stage full name)
[0090] Function: Specify the stages to be processed. A total of three stages are supported: template, style, and script, separated by English half-width commas
[0091] Default behavior: If not passed, all processes will be executed by default
[0092] 4. Help information parameters:
[0093] Short format: ˋ-hˋ (help abbreviation)
[0094] Long format: ˋ--helpˋ (help full name)
[0095] Function: Display detailed help information for this tool
[0096] Each parameter has two representations: short format (single letter) and long format (full word), and users can choose to use either according to their personal preferences. The short format uses a single hyphen (`-`), while the long format 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, the 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 this code conversion process:
[0099] (1) Command line parameter parsing.
[0100] As described above, the command tool of this application supports carrying parameters in the command line code to customize the code conversion process. This step is to pre-parse the parameters specified by the user to guide the 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. This library provides a concise API that can easily define and parse command line parameters.
[0102] Through this command line parameter parsing library, the tool of this application first defines the command line parameters supported by the tool of this application: c (config) is used to receive the path of the configuration file specified by the user; f (files) is used to receive the path of the file to be converted specified by the user; s (stages) is used to receive the necessary processing stages of the code conversion 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 through a chained call to the parse API.
[0103] In an exemplary embodiment, before step 102, it further includes: a configuration file path parameter verification process, a list of file paths to be converted parameter verification process, and a necessary processing stage parameter verification process for code conversion.
[0104] Among them, the process of validating the configuration file path parameter is as follows: Validate 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; Validate 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 cannot be read successfully, or the file content is empty, terminate the process, and output different error messages in the terminal: "Configuration file not found", "Failed to read configuration file content", 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, temporarily store the read configuration content in a global variable to complete the process of validating the configuration file path parameter; If the user neither specifies the configuration file path parameter in the command line nor configures the USER_DEFINED_CONFIG_PATH environment variable in the running environment, in the current working directory where the user executes the command line, automatically call the file creation API and file writing API built into the code running environment to generate a configuration file with the file name "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 process of validating the configuration file path parameter; If the configuration file fails to be written, terminate the process, and output the error message "Failed to write configuration file" in the terminal.
[0105] The process of validating the list of file paths to be converted is as follows: If the user does not specify the list of file paths to be converted, directly terminate the process, and output the error message "No files to process" in the terminal; If the user specifies the list of file paths to be converted, use the built-in API of the running environment to split the parameter value of the string type, with the split point being the English half-width comma, and obtain a list of file paths; Traverse the list of file paths, process the leading and trailing spaces of each file path string one by one, and validate whether the processed file path is a legal Vue file path; If no legal Vue file paths are found after verification and processing, directly terminate the process, and output the error message "No legal Vue file paths specified" in the terminal; If there are both legal Vue file paths and illegal Vue file paths, continue to execute the next process, and output the warning message "There are illegal paths: {Path A}|{Path B}|..." in the terminal; If all are legal Vue file paths, normally continue to execute the next process; Temporarily store the list of file paths to be converted that are verified as legal in a global variable.
[0106] The parameter verification process for the mandatory code conversion phase is as follows: If the user does not specify the parameters for the mandatory code conversion phase, the parameter verification process for the mandatory code conversion phase is directly skipped, and in the subsequent conversion process, full-phase conversion is performed, and the full-phase list ["style", "script", "template"] is temporarily stored in the global variable; if the user specifies the parameters for the mandatory code conversion phase, the parameter value of this string type is cut through the built-in API of the running environment, and the cut point is the English half-width comma, and a phase list is obtained; traverse this phase list, process the leading and trailing spaces of the phase string one by one, and verify whether the processed phase is a legal phase; the legal phases include ["style", "script", "template"]; "style" is the "style" phase, "template" is the "template" phase, and "script" is the "script" phase; if no legal phase is found after processing and verification, the process is directly terminated, and an error message "no legal stage specified" is output in the terminal; if there are both legal phases and illegal phases, the next process is continued, and a warning message "illegal stage(s) will be ignored: {path A}|{path B}|..." is output in the terminal; if all are legal phases, the next process is normally continued; the list of phases verified as legal is temporarily stored in the global variable.
[0107] Further, (2) Command-line parameter check.
[0108] Based on the above (1), the present application has obtained the command-line parameters input by the user. However, due to the uncertainty of the user's command-line parameter input, these parameters need to be checked and verified through this step before the conversion process is officially started.
[0109] First, the present application will verify the configuration file path parameter c (config). In this verification step, if the user does not specify the configuration file path, the present 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 attempt to load and read it by calling the built-in import method of the running environment. If the file path does not exist / the file content reading fails / the file content is empty, the present application will terminate the process and output different error messages in the terminal: "configuration file not found" / "failed to read configuration file content" / "configuration file content is empty"; if the file path exists and the configuration content in the file is successfully read, the read configuration content will be temporarily stored in the global variable for use in subsequent processes.
[0110] In addition to the above content, the following fallback solution is built into this verification step: If the user neither specifies the configuration file path parameter in the command line nor configures the USER_DEFINED_CONFIG_PATH environment variable in the running environment, a configuration file named "vue-sfc-to-jsx.config.ts" will be automatically generated in the current working directory where the user executes the command line by calling the file creation and writing APIs built into the code running environment. The content of the file 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 parameter f (files) of the file path list to be converted - this parameter is a necessary parameter for the subsequent code execution of this application, and it allows multiple file paths to be specified simultaneously, separated by English half-width commas - during this verification step. If the user does not specify this parameter, this application will directly terminate the process and output the error message "No files to process" in the terminal. If the user specifies this parameter, this application will use the built-in API of the running environment to split the parameter value of this string type, with the split point being the English half-width comma, and finally obtain a file path list. For example, splitting the string "a.doc,b.doc" by the English half-width comma will result in the file path list ["a.doc","b.doc"].
[0112] This application will traverse this file path list, process the leading and trailing spaces of each 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 paths 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 "There are illegal paths: {Path A}|{Path B}|..." in the terminal; if all are legal paths, this application will continue to execute normally. This step will finally temporarily store the list of verified legal file paths to be processed in a global variable for use in subsequent processes.
[0113] Finally, this application will verify the parameter s (stages) in the necessary processing stage of code conversion. In this verification step, 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 use the built-in API of the running environment to split the parameter value of this string type. The splitting point is the English half-width comma, and finally a stage list will be obtained. This application will traverse this stage list, process the leading and trailing spaces of each 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 an 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 "Illegal stages will be ignored: {Path A}|{Path B}|..." in the terminal; if all are legal stages, this application will continue to execute normally. This step will finally temporarily store the read stage list in a global variable - if the user does not specify this parameter, the full-stage list ["style", "script", "template"] will be temporarily stored in this variable for use in subsequent processes.
[0114] Before starting the introduction of the specific code conversion processes for template, script, and style, this application first clarifies the core technology of this application: conversion based on AST.
[0115] The core technology of this application is to achieve the automatic conversion of Vue files to TSX files based on AST (Abstract Syntax Tree).
[0116] AST is a tree-like representation of the abstract syntax structure of source code, which can clearly express the structure and components of the code. It is the basis for this application to perform code parsing and conversion. By constructing and operating on the AST, the code structure can be deeply understood and transformed, so as to achieve accurate code conversion.
[0117] Regardless of which part of the template, script, or style in the Vue file, its unified code conversion process remains the same, which is as follows:
[0118] Generation of AST: Use a specific tool library to parse the specific part of the Vue file and generate the corresponding abstract syntax tree (AST).
[0119] AST Transformation: Targeted code node transformation processing is performed on the different ASTs generated for different parts of the Vue file, including a series of optimization measures such as grammar improvement, redundant node merging, and expression simplification.
[0120] AST Generation and Output: The transformed template AST, script AST, and style AST are respectively generated into complete jsx code snippets, script code snippets, and style code snippets. Subsequently, further optimization and code formatting are carried out to ensure that the generated code snippets comply with the best practices of TypeScript and JSX.
[0121] By parsing, transforming, and generating around the AST, the technical solution of this application can achieve precise and efficient transformation of Vue files. The AST provides in-depth understanding and manipulation capabilities of the code structure, enabling the transformation process to maintain the logical consistency and readability of the code.
[0122] In an exemplary embodiment, step 103 can be replaced by the following steps.
[0123] Use the createSourceFile API in the TypeScript class component of the TypeScript tool library to parse the script code snippet to determine the script AST; the script AST includes all syntax nodes in the Vue file, and the syntax nodes include data, methods, computed 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 script AST in breadth-first traversal order to determine the type of each syntax node; parse different types of syntax nodes to construct a new script AST; based on the new script AST, call the printFile API in the TypeScript tool library to generate the transformed script code snippet.
[0124] Furthermore, parse different types of syntax nodes to construct a new script AST, specifically including: if the currently traversed syntax node is a PropertyAssignment node and the name identifier string of this PropertyAssignment node is "name", then take out and temporarily store the node initialization value corresponding to this PropertyAssignment node as the component name of the subsequent new jsx code snippet; if the currently traversed syntax node is a PropertyAssignment node, the name identifier string of this PropertyAssignment node is "data", and the initialization value node of this PropertyAssignment node is a method node, parse the AST node corresponding to the return statement of this method node, and recursively traverse this AST node to parse out the first object property-value pair list; call the typescript createPropertyDeclaration API to generate new first-class property nodes for each element in the first object property-value pair list as part of the subsequent new jsx AST; if the currently traversed syntax node is a MethodDeclaration node and the name identifier string of this MethodDeclaration node is "data", parse the AST node corresponding to the return statement of this MethodDeclaration node, and recursively traverse this AST node to parse out the second object property-value pair list from it; call the typescript createPropertyDeclaration API to generate new second-class property nodes 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 this PropertyAssignment node is one of "components", “filters” or “directives”, then temporarily store this AST node respectively for subsequent reuse as part of the new jsx AST; if the currently traversed syntax node is a PropertyAssignment node, the name identifier string of this PropertyAssignment node is "computed", and the initialization value node of this PropertyAssignment node is an object type node, then recursively traverse the object AST node to parse out the property names, property calculation methods, and property accessor types corresponding to each computed property;Call the createGetAccessorDeclaration method or the createSetAccessorDeclaration method to generate a new class accessor property node corresponding to the computed property, which is part of the subsequent new jsx AST; if the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of this PropertyAssignment node is "methods", and the initialization value node of this PropertyAssignment node is an object type node, then recursively traverse the object AST node to parse out the method name, method input parameters, 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, which is part of the subsequent new jsx AST; if the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of this PropertyAssignment node is "props", and the initialization value node of this 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, which is part of the subsequent new jsx AST; if the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of this PropertyAssignment node is "props", and the initialization value node of this PropertyAssignment node is an array type node, then traverse the array AST node and call the createPropertyDeclaration method for each array element to generate a new second-class property declaration node corresponding to the component prop, which is part of the subsequent new jsx AST; if the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of this PropertyAssignment node is "watch", and the initialization value node of this 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, which serves as part of the subsequent new jsx AST; if the currently traversed syntax node is a `PropertyAssignment` node, and the name identifier string of this `PropertyAssignment` node is any one of "beforeCreate", "created", "beforeMount", "mounted", "beforeUpdate", "updated", "activated", "deactivated", "beforeDestroy", "destroyed", and "errorCaptured", it indicates that the current node is a Vue component lifecycle hook node. Parse the identifier name, method parameters, method body, and identifier corresponding to the lifecycle method from this 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, which serves as part of the subsequent new jsx AST; if the currently traversed syntax node is an `ExportAssignment` node, it indicates that the current node is a default export node. Perform a comprehensive recursive traversal on the expression sub-node of this default export node and skip processing this default export node; if the currently traversed syntax node is an unprocessed node, there is no need to perform a recursive traversal, just temporarily store this unprocessed node for later use as part of the new jsx AST; the unprocessed nodes are `ImportDeclaration` nodes, `ExportDeclaration` nodes, or `VariableStatement` nodes; construct a new script AST based on the component name of the new jsx code snippet and a part of the new jsx AST.
[0125] The script code converter is further described below.
[0126] During the process of converting a Vue file to a TSX file, the script part needs special handling because it involves converting the component logic and data management of Vue into code that conforms to TypeScript and TSX syntax. This process involves parsing the original JavaScript or TypeScript code and converting it into the form of a TypeScript class component using the `vue-tsx-support` and `vue-property-decorator` tool libraries. The specific conversion steps are as follows:
[0127] 1. Parse the script code:
[0128] Use the createSourceFile API of the TypeScript library typescript to parse the script code and obtain the script abstract syntax tree (AST). All syntax nodes in the original Vue file will be included in the script AST, and the syntax nodes include data, methods, computed properties, lifecycle hooks, etc.
[0129] 2. Traverse the existing script AST to generate a new script AST:
[0130] This step is the most core step in the script code conversion process. Given the huge differences in syntax before and after the script code conversion, it is extremely difficult to directly modify the nodes on the existing script AST. Therefore, this application adopts a solution to traverse and analyze the script AST generated in the previous step to gradually generate a new script AST, and its specific process is described as follows:
[0131] First, this application uses the transform method of the TypeScript library typescript to recursively traverse the script AST generated in step 1 above. This API will traverse each syntax node of the script AST in breadth-first traversal order.
[0132] Since there are various types of syntax nodes in a script code snippet, this application will also combine conditional control statements to perform different parsing and processing 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 (property assignment) node and the name identifier string of the node is "name", then take out and temporarily store the initial value of the node corresponding to the PropertyAssignment node as the component name of the subsequent new jsx code snippet.
[0134] If the currently traversed syntax node is a PropertyAssignment (property assignment) node, the name identifier string of the node is "data", and the initial value node of the node is a method node, then parse out the AST node corresponding to the return statement of the method node, recursively traverse it, parse out the object property-value pair list from it, and call the typescript createPropertyDeclaration API to generate new class property nodes for each element of the list as part of the subsequent new jsx AST.
[0135] If the currently traversed syntax node is a MethodDeclaration (method declaration) node and the name identifier string of the node is "data", then parse the AST node corresponding to the return statement of the node, recursively traverse it, parse out the list of object property-value pairs from it, and call the typescript createPropertyDeclaration API to generate new class property nodes for each element of the list, which will be part of the subsequent new jsxAST.
[0136] If the currently traversed syntax node is a PropertyAssignment (property assignment) node and the name identifier string of the node is one of "components", "filters", or "directives", then temporarily store the AST node respectively for subsequent reuse as part of the new jsxAST.
[0137] If the currently traversed syntax node is a PropertyAssignment (property assignment) node and the name identifier string of the node is "computed" and the initialization value node of the node is an object type node, then it is necessary to recursively traverse the object AST node, parse out the three types of information of the property name, property calculation method, and property accessor type corresponding to each computed property from it, and call the createGetAccessorDeclaration or createSetAccessorDeclaration method to generate new class accessor property nodes for these computed properties respectively, which will be part of the subsequent new jsxAST.
[0138] If the currently traversed syntax node is a PropertyAssignment (property assignment) node and the name identifier string of the node is "methods" and the initialization value node of the node is an object type node, then it is necessary to recursively traverse the object AST node, parse out the four types of information of the method name, method input parameters, function body, and modifiers corresponding to each component method from it, and call the createMethodDeclaration method to generate new class method nodes for these component methods respectively, which will be part of the subsequent new jsxAST.
[0139] If the currently traversed syntax node is a PropertyAssignment (property assignment) node, and the name identifier string of the node is "props" and the initialization value node of the node is an object type node, then it is necessary to recursively traverse the object AST node, parse out two kinds of information: the prop identifier name corresponding to each component prop and the prop initialization value, and call the createPropertyDeclaration method to generate new class property declaration nodes for these component props respectively, as part of the subsequent new jsxAST.
[0140] If the currently traversed syntax node is a PropertyAssignment (property assignment) node, and the name identifier string of the node is "props" and the initialization value node of the 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 respectively, as part of the subsequent new jsxAST.
[0141] If the currently traversed syntax node is a PropertyAssignment (property assignment) node, and the name identifier string of the node is "watch" and the initialization value node of the node is an object type node, then it is necessary to recursively traverse the object AST node, parse out five kinds of information: the watcher identifier name corresponding to each component watcher, the watcher method parameters, the watcher method body, the watcher object, and the watcher configuration, and call the createMethodDeclaration method to generate new class method declaration nodes for these component watchers respectively, as part of the subsequent new jsxAST.
[0142] If the currently traversed syntax node is a PropertyAssignment (property assignment) node, and the name identifier string of the node is any of "beforeCreate", "created", "beforeMount", "mounted", "beforeUpdate", "updated", "activated", "deactivated", "beforeDestroy", "destroyed", "errorCaptured", it indicates that the current node is a Vue component lifecycle hook node. In this case, only four types of information, namely the identifier name, method parameters, method body, and identifier corresponding to the lifecycle method, need to be parsed from this node, and the createMethodDeclaration method is called to generate new class method declaration nodes for each lifecycle hook, which will be used as part of the subsequent new jsxAST.
[0143] If the currently traversed syntax node is an ExportAssignment (export assignment) 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 of the expression sub-node of this node, while skipping the processing of the node itself.
[0144] If the currently traversed syntax node is an ImportDeclaration (import declaration) node, an ExportDeclaration (export declaration) node, a VariableStatement (variable statement) node, or other nodes not processed above, there is no need for recursive traversal. Only the node needs to be temporarily stored and left for subsequent use as part of the new jsxAST.
[0145] After the AST analysis through the above recursive combination with conditional control statements, in this step of the present application, there will be component name information, a list of new class method declaration nodes, a list of new class property declaration nodes, and a list of other nodes that cannot be specially processed or do not need to be processed. These information will be used to generate a new scriptAST:
[0146] First, check whether there is any node with the name of "components", "filters", or "directives" in the temporarily stored node list. If there is, use createDecorator combined with the createCallExpression API in advance to generate the AST corresponding to the decorator statement in the form of "@Component({components:{xxx}})"; if not, only call createDecorator to generate the AST corresponding to the decorator statement in the form of "@Component".
[0147] Secondly, call the createModifierAPI to generate the necessary export and default modifiers for the new jsxAST respectively.
[0148] For the jsx part of the TSX file, since it needs to be embedded in the render method of a 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 this method to the predefined placeholder string "==========jsx here==========", which is convenient for replacing it with the actual jsx code snippet in the subsequent process.
[0149] For the TSX file, its component form is a class component. Therefore, finally, the createClassDeclaration, createHeritageClause, and createExpressionWithTypeArguments APIs need to be used, and parameters such as the component name, the list of class property declaration nodes, and the list of class method declaration nodes are passed in reasonably.
[0150] Filter the node temporary storage list, extract the ImportDeclaration nodes, ExportDeclaration nodes, and VariableStatement nodes from it to form a node list, and call the updateSourceFileAPI, passing this node list and the newly generated classAST as parameters into this API as input parameters to obtain 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 present application has obtained a new scriptAST. At this time, only the printFileAPI provided by the typescript tool library needs to be called to generate the code snippet. Thus, the script code conversion is completed.
[0153] In an exemplary embodiment, step 104 can be replaced by the following steps.
[0154] Use the parse API of the @vue / compiler-dom library to parse the template code snippet and obtain the template AST; the template AST includes all types of nodes in the component template; the types of nodes include tag nodes, text nodes, directive nodes, and component nodes; traverse the template AST, using the depth-first recursive order, combined with conditional control statements, perform different parsing processes for different types of token nodes, and build a new jsx AST based on the API of the @babel library; based on the new jsx AST, call the generator API in the @babel library to generate a jsx code snippet; the jsx code snippet is the converted template code snippet.
[0155] Further, traverse the templateAST, using the depth - first recursive order, combined with conditional control statements, perform different parsing and processing for different types of token nodes, and construct a new jsxAST based on the API of the @babel tool library, specifically including: If the currently traversed token node is an ELEMENT node, determine the props attribute in the node AST; this props attribute includes all the attribute node lists in the ELEMENT node; classify each attribute node in the attribute node list by combining conditional control statements to determine the attribute information list; traverse the attribute information list and generate new jsx AST attribute nodes corresponding to each element in the attribute information list; If the currently traversed token node is an ELEMENT node, determine the children attribute in the node AST, recursively process the child node list of this ELEMENT node, and determine the new jsxAST nodes of each child node and the instruction type attribute to be processed; traverse the child node list in forward order to process the for loop instruction, call the parseExpressionAPI to convert the attribute value string into a loop expression AST, and parse out the loop object and loop parameters from it, and then use the jsxExpressionContainer of the @babel tool library in combination with multiple APIs to construct an AST node corresponding to the code in the form of "{xxx.map(y => {return child node})}"; the multiple APIs include callExpression, arrowFunctionExpression, and blockStatement; where, {xxx.map(y => {return child node})} is an example, xxx is the "loop object" mentioned above, y is the "loop parameter" mentioned above, xxx.The "map" is a loop statement; traverse the list of child nodes in reverse order, group the child nodes with conditional pairing relationships, and for the child nodes contained in these groups, construct an AST node corresponding to the code in the form of "{a? child node 1: child node 2}" by combining the attribute value strings of each child node; where "{a? child node 1: child node 2}" is a conditional control code block; a is the judgment condition in the conditional control statement; extract the "tag" attribute from the node AST, and determine whether the "tag" attribute is an HTML native tag name; if so, do nothing, if not, regard the ELEMENT node as a component node, and format the name of the "tag" attribute in camelCase; call the jsxElement API, and pass in the processed "tag" attribute name, the processed list of attribute nodes, and the processed list of child nodes as parameters to generate a new jsx node; if the currently traversed markup node is a TEXT node, call the jsxText API to generate a new jsx node for the TEXT node; if the currently traversed markup node is an INTERPOLATION node, parse the interpolation content string from the node AST, then call the parseExpression API to parse the INTERPOLATION node into an expression AST, and finally call the jSXExpressionContainer API to generate a new jsx node for the INTERPOLATION node; based on the API of the @babel tool library, construct a new jsx AST according to all the new jsx nodes.
[0156] The following further explains the template code converter.
[0157] In the process of converting a Vue file to a TSX file, the template part needs to be specially processed because it involves the conversion from Vue's template syntax to JSX syntax, and the @vue / compiler-dom tool library and the @babel tool library need to be used in this process. 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 to obtain the template AST. All types of nodes in the component template, such as tag nodes, text nodes, directive nodes, and component nodes, will be included in the template AST.
[0160] 2. Traverse the existing template AST to generate a new jsx AST:
[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 toolkits used for parsing code fragments and generating code fragments, directly modifying nodes on the existing template AST cannot meet the conversion requirements. Therefore, this application adopts the solution of traversing and analyzing the template AST generated in the previous step to gradually generate a new jsxAST for generating new code fragments. The specific process is described as follows:
[0162] First of all, it should be clear that due to the HTML language characteristics of template code and its writing restrictions in Vue, there is a biggest difference compared with script code: there is only one root node in the AST, and the rest of the nodes are nested child nodes of this root node. Therefore, this application will use the depth-first recursive order and combine conditional control statements to perform different parsing and processing on different types of token nodes to prepare for generating the final converted jsx code. The specific processing method is as follows:
[0163] If the currently traversed token node is an ELEMENT (element) node, since there will be information such as attributes, directives, and events in the ELEMENT node, further processing is required for accurate conversion:
[0164] 1) First, take out the props attribute in the node AST. This attribute will contain a list of all attribute nodes in the ELEMENT node. For each attribute node among them, 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 in the conventional writing method. Only the attribute name and the corresponding attribute value need to be parsed from the node AST. However, due to the characteristics of SCSS module, when processing the node attribute named style, its attribute value needs to be processed specifically: if the attribute value is in the global class name list obtained after the style converter analyzes, the original attribute value remains unchanged; if the attribute value is in the local class name list obtained after the style converter analyzes, the attribute value is concatenated into a new string "styles.attribute value"; for other named node attributes, the original attribute value remains unchanged.
[0166] If the node type of the current attribute node is DIRECTIVE (instruction), it represents that it is the node attribute of the directive binding writing method, such as v-if, v-else-if, v-else, v-for, v-bind, v-model, v-on, v-show, etc. For directive attributes such as v-if, v-else-if, v-else, v-for, v-model, etc., since these attributes mainly have logical capabilities, it is necessary to parse the directive type and attribute value from the node AST; 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 directive attribute needs special processing. Since this directive is essentially a syntactic sugar for two attribute nodes, v-bind:value and v-on:input, after parsing the attribute value from the node AST, two sets of attribute information, [value (as the attribute name), attribute value] and [input, attribute value assignment function (obtained by replacing with a preset string template)], need to be constructed for subsequent node generation.
[0167] 2) After traversing and processing the props attribute node list in the node AST, an attribute information list will be obtained. This step needs to traverse this attribute information list and generate new jsxAST attribute nodes for each list element:
[0168] If the current attribute information object does not contain a directive type field, it means that the current attribute can be directly generated in the simplest jsx attribute form. Using the jsxAttribute and jsxExpressionContainer of the @babel tool library can achieve this purpose; after generating the new jsx attribute node, this application will also filter it out from the attribute information list for convenient processing in subsequent steps.
[0169] If the current attribute information object contains a directive type field, its processing will be temporarily ignored and it will be retained in the attribute list for the upper-level loop to process.
[0170] 3) As described above, this processing flow is a recursive processing flow. Therefore, after processing the props attribute information of this node, the children attribute in the AST of this node is taken out, and the list of child nodes of this node is recursively processed. According to this processing flow, after processing the list of child nodes, the new jsxAST nodes of each child node and the directive type attributes to be processed will be obtained.
[0171] 4) Start to uniformly process the child nodes with instruction type attributes in the child node list. The reason for processing them at this level of traversal is that if, else, and else-if are conditional control instructions. From the perspective of the processing level of child nodes, a child node itself cannot perceive whether its sibling nodes have paired conditional control statements. Only the upper-level traversal can handle it from a higher perspective. First, traverse the child node list in the forward order to process the for loop instructions. Convert the attribute value string to a loop expression AST by calling the parseExpression API, and parse out the loop object and loop parameters from it. Then, use the jsxExpressionContainer of the @babel tool library in combination with APIs such as callExpression, arrowFunctionExpression, and blockStatement to construct an AST node corresponding to the code in the form of "{xxx.map(y => {return child node})}"; Second, traverse the child node list in the reverse order to group the child nodes with conditional pairing relationships. For example, group adjacent child nodes with if and else conditional control instructions, and for the child nodes included in these groups, combine the attribute value strings parsed from each child node in the previous step to construct an AST node corresponding to the code in the form of "{a? child node 1 : child node 2}".
[0172] 5) After the above steps, the attributes of the node and the child node list 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 an html native tag name. If not, regard the node as a component node and format the tag name in camel case. If so, do not do any processing; Second, call the jsxElement API and pass in the processed tag name, attribute node list, child node list, etc. as parameters to generate a new jsx node.
[0173] 6) After the above steps, the processing of the nodes at this level is completed. However, since this processing process is a recursive process, at the end of the process, the new jsx node processed this time and the list of instruction type attributes to be processed by the upper-level traversal need to be returned in the form of return.
[0174] If the currently traversed markup node is a TEXT (text) node, since such a node is itself a pure text string and does not need to be converted, call the jsxText API to generate a new jsx node for it and then 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 Vue template syntax, and the processing flow is relatively simple. Parse the interpolation content string from the node AST, then call the parseExpression API to parse it into an expression AST, and finally call the jSXExpressionContainer API to generate a new jsx node for it and return it in the form of return.
[0176] Since the above processing flow is in the form of recursive combination with conditional control, there will be a relationship of mutual nesting and combination between the processing steps. For example, when recursively processing the list of child nodes, there may be both INTERPOLATION nodes, TEXT nodes, and ELEMENT nodes in the list of child nodes. Therefore, the above processing flow is not always executed in the described order during actual execution. However, in any case, based on the characteristic that "there is only one root node in the template AST, and the rest of the nodes are nested child nodes of this root node", after the above processing, this application will obtain 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 jsx AST:
[0178] Through the above steps, this application has obtained a new jsx AST. At this time, only need to call the generator API provided by the @babel tool library to generate a jsx code snippet. Thus, the conversion of the template code is completed.
[0179] In an exemplary embodiment, step 105 can be replaced by the following steps.
[0180] Use the PostCSS tool library and the PostCSS-SCSS plugin to parse the style code snippet to determine the style AST; use the walkRules API in the PostCSS tool library to traverse the nodes in the style AST, and replace the ::v-deep pseudo-class in the style AST with the :global pseudo-class to construct a new style AST; based on the new style AST, call the process API provided by the PostCSS tool library to generate the converted style code snippet.
[0181] Furthermore, use the walkRules API in the PostCSS tool library to traverse the nodes in the style AST, and replace the ::v-deep pseudo-class in the style AST with the :global pseudo-class to construct a new style AST, which specifically includes: determining whether the currently traversed node is a node of the rule type; if the currently traversed node is a node of the rule type, use the processSync of the PostCSS tool library in combination with the selectorParser and the walkPseudos API to recursively traverse the pseudo-class selectors included 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 use this pseudo-class node as the target pseudo-class to be processed by the converter, and call the selectorParser.pseudo API in combination with the replaceWith API 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 this pseudo-class node; if the currently traversed node is not a node of the rule type, then ignore this node; until all nodes in the style AST are traversed to construct a new style AST.
[0182] Furthermore, based on the new style AST, call the process API provided by the PostCSS tool library to generate the converted style code snippet. After that, it also includes: calling the walkRules API of PostCSS to traverse the rule nodes of the new style AST; traversing the selectors list of the rule nodes, and for each list element in the selectors list, calling the postcssSelectorParser in combination with the processSync API to perform secondary parsing on this list element to determine the selector list corresponding to this list element, and set a local variable scope, initialize the local variable scope to local, and obtain the local class name list; calling the walk API to traverse the selector list to obtain the global class name list.
[0183] The following further explains the style code converter.
[0184] Since this application supports the conversion solution from a Vue (v2) + SCSS project to a Vue (v2) + TSX + SCSS module project, for the style code part, the SCSS preprocessor is used both before and after the conversion. Therefore, different from the previous two converters, the code conversion of the style part focuses on removing the unique syntax in Vue files and converting it into legal syntax in SCSS module files. The specific steps are as follows:
[0185] 1. Parse the style code:
[0186] Use the PostCSS tool library and the PostCSS-SCSS plugin to parse the style code - PostCSS is a powerful tool that can process and transform CSS, and the PostCSS-SCSS plugin can parse SCSS syntax - through the postcss of PostCSS and the process API, the extracted SCSS style block can be parsed 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 style AST and replace the ::v-deep pseudo-class with the :global pseudo-class:
[0188] In the scoped styles of Vue, the ::v-deep pseudo-class is used to deeply select the styles of child components, pointing to descendant components and applying styles. Since the SCSS module file does not support features like ::v-deep, and most of the application scenarios of ::v-deep are to override the styles of child components, this application will convert it to the :global pseudo-class supported by the SCSS file. The specific conversion process is as follows:
[0189] First, the PostCSS tool library provides the walkRules API for traversing AST nodes. This application only needs to rely on the traversal of this API to determine whether the currently traversed node is a node of the rule type. If not, the node is ignored; if so, the subsequent steps are executed.
[0190] If the currently traversed node is a node of the rule type, use the processSync of the PostCSS tool library in combination with the selectorParser and walkPseudos API to recursively traverse the pseudo-class selectors contained in the selector field selector of this 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 combination with the replaceWith API to replace this pseudo-class with :global.
[0192] If the name of the currently traversed pseudo-class node is not ::v-deep, ignore this node.
[0193] As mentioned above, the style code conversion task is relatively simple, and the above is the core conversion process.
[0194] 3. Generate a new style code snippet according to the new styleAST:
[0195] Through the above steps, the present application has obtained a new styleAST. At this time, only need to call the process API provided by the PostCSS tool library to generate a style code snippet. Thus, the style code conversion ends.
[0196] 4. Analyze the new style code snippet to obtain various class name scopes:
[0197] For the converter itself, the above three steps already meet the conversion requirements. However, for the functional integrity of the tool described in the present application, the converter also needs to additionally support the class name scope analysis ability.
[0198] SCSS module (or CSS module) is a technology that encapsulates CSS styles in modules, aiming to solve the problem of the CSS global namespace and avoid style conflicts and pollution. When using SCSS module, class names are usually accessed in the form of object properties, such as styles.xxxx, because after the project code is compiled and packaged, the style class names will be localized and have unique identifiers to ensure that they only take effect in specific components or modules. For example, the class names in a 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 names are unique globally and will not conflict with class names in other modules.
[0199] However, in some special scenarios, the use of global class names cannot be avoided. SCSS module supports identifying such global class names through the special pseudo-class :global, and when using it, just write class="button". The final usage in HTML will be <button class="button">ClickMe< / button> .
[0200] The pre-conversion technology stack supported by this application is Vue (v2) + SCSS. In this technology stack, class names can be used directly by writing class="xxx" without accessing them through object properties like styles.xxx.
[0201] Then, if the tool described in this application does not handle such class names specially during conversion, the class names in the converted code will all be in the form of class="xxx" and cannot be associated with local class names, making the code unable to run directly.
[0202] To solve this problem, this converter needs to analyze the new style fragment after conversion again - obtain the local class name list and the global class name list. When converting the template code, it is necessary to determine whether to modify the class name usage to styles.xxx or keep xxx unchanged accordingly:
[0203] First, obtain the style AST through the postcss.parse API of PostCSS.
[0204] Call the walkRules API of PostCSS to traverse the rule nodes of the AST.
[0205] Traverse the selectors list of the rule node. For each list element, call the postcssSelectorParser in combination with the processSync API to parse the list element again to obtain the final selector list corresponding to the element. After setting the local variable scope and initializing it to local, call the walk API to traverse the selector list.
[0206] If the currently traversed selector node is of the pseudo-class type, it is processed in depth through conditional control statements:
[0207] If the pseudo-class name of the current node is ":global", modify the value of the local variable scope to global; if the pseudo-class name of the current node is ":local", modify the value of the local variable scope to local. After the above conditional judgment, check whether the nodes field of the current pseudo-class node is a non-empty list. If it is non-empty, traverse the list and store the key-value pairs formed by the class names involved in the list and the current scope value.
[0208] If the currently traversed selector node is of the class type, store the key-value pairs formed by the class name and the current scope value.
[0209] Through the above process, this application will finally obtain a list of key-value pairs with the class name: scope. For the convenience of subsequent use, this step will traverse the list again and group the class names by the scope value, so as to obtain a local class name list and a global class name list respectively and temporarily store them, which can be used to support the work of the template converter.
[0210] In an exemplary embodiment, step 106 can be replaced by the following steps.
[0211] Obtain the original Vue file name through the built-in API of the running environment; determine whether there is a "style" phase in the phase list; if so, write the converted style code snippet into a 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 running environment; if the file writing fails, execute the next process normally and output a warning message in the console terminal: "Failed to create new SCSS module file: {xxx.module.scss}"; if the file writing is successful, output a prompt message in the console terminal: "New SCSS module file: {xxx.module.scss} created successfully", and temporarily store the SCSS module file name in a local variable; if not, skip the "style" phase; determine whether there is a "template" phase in the phase list; if not, directly skip the "template" phase and continue to execute the subsequent steps based on the converted script code snippet; if so, determine whether there is a "script" phase in the phase list; if there is a "script" phase, call the built-in string replacement API of the running environment to replace the placeholder string "==========jsx here==========" set in the converted script code snippet with the new jsx code snippet, and continue to execute the subsequent steps using the replaced script code snippet; if the "script" phase does not exist in the phase list, embed a simple version of the script code and use the same placeholder string "==========jsx here==========" at the position where jsx is required; if both the "template" phase and the "script" phase exist in the phase list, generate a new TSX file for the converted script code snippet; the new file name of the new TSX file is obtained by converting the original Vue file name to camelCase and appending 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 a new SCSS module file has not been successfully generated in this conversion, and a new TSX file will be directly generated; if there is a value, generate a reference code statement "import styles from '. / xxx.module.scss';" for the new SCSS module file, and insert this reference code statement at the front of the script code snippet; write this script code snippet into a 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 running environment; if the file writing fails, execute the subsequent steps normally and output a warning message in the console terminal: "New TSX file: {xxx.The creation of the tsx file fails"; if the file is successfully written, it indicates the successful completion of this round of traversal. The following prompt will be output on the console terminal: "The new TSX file: {xxx.tsx} is successfully created". A new code file will be generated, and the next round of traversal will continue.
[0212] In summary, the overall steps of this application are as follows:
[0213] The legal file path list obtained in the previous step will be retrieved and processed by traversing each one:
[0214] a. Read the file content according to the file path and parse it using the parseComponent API of the vue-template-compiler tool library. As described above, a regular Vue file consists of three parts: template, script, and style. The function of the parseComponent API is to parse the code snippets of these three parts from the file content, namely the template code snippet, the script code snippet, and the style code snippet. Similarly, as described above, these three parts are actually written in three different programming languages and cannot be uniformly processed. In this application, these three parts will be converted separately later.
[0215] b. Retrieve the stage list obtained in the previous step. If the "style" stage does not exist in this list, or the style code snippet is an empty string, this step will be skipped directly; otherwise, the style code snippet will be normally converted.
[0216] c. Retrieve the stage list obtained in the previous step. If the "script" stage does not exist in this list, or the script code snippet is an empty string, this step will be skipped directly; otherwise, the script code snippet will be normally converted.
[0217] d. Retrieve the stage list obtained in the previous step. If the "template" stage does not exist in this list, or the template code snippet is an empty string, this step will be skipped directly; otherwise, the template code snippet will be normally converted.
[0218] e. After steps b, c, and d are completed respectively, at least one of the new template code snippet (i.e., the jsx code snippet), the script code snippet, and the style code snippet will be obtained. In this step, these three new code snippets need to be combined and processed to generate a new code file:
[0219] First, for the newly generated code files, their names are all based on the original file name. Therefore, the original file name is obtained here through the built-in API of the running environment.
[0220] Take out the stage list obtained in the previous step. If the "style" stage does not exist in this list, directly skip this step; otherwise, directly generate a new SCSS module file for the style code snippet. The new file name is formed by converting the original file name to kebab-case format (referring to the format formed by connecting pure lowercase English words with hyphens) and then appending the ".module.scss" suffix, such as "a-b-c.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 running environment. If the file writing fails, this application will normally execute the subsequent steps and output a warning message in the console terminal: "Failed to create the new SCSS module file: {xxx.module.scss}"; if the file writing is successful, a prompt message will be output in the console terminal: "Successfully created the new SCSS module file: {xxx.module.scss}", and the SCSS module file name will be temporarily stored in a local variable and then continue to execute the subsequent steps.
[0221] Take out the stage list obtained in the previous step. If the "template" stage does not exist in this list, directly skip this step and continue to execute the subsequent steps using the converted script code snippet obtained in the previous step; otherwise, determine whether the "script" stage exists in the list. If the "script" stage exists in the list, it is necessary to call the built-in string replacement API of the running environment to replace the special "==========jsx here==========" placeholder string in the new script code snippet with the new jsx code snippet, and continue to execute the subsequent steps using the replaced script code snippet; if the "script" stage does not exist in the list, considering the feature that jsx code in a TSX file needs to be embedded inside the script code, this application will build a simple version of the script code, and use the same "==========jsx here==========" placeholder string at the position where jsx needs to be embedded. And in this step, as a fallback solution for the case without the "script" stage, it is provided for the new jsx code snippet to replace the placeholder string and then be embedded, and continue to execute the subsequent steps using the replaced built-in script code snippet.
[0222] Take out the stage list obtained in the previous step. If neither the "template" stage nor the "script" stage exists in this list, directly skip this step; 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 to camelCase and appending the.tsx suffix, such as "helloWorld.tsx". Before writing to the file, it is also necessary to determine whether the local variable of the SCSS module file name has a value. If it has no value, it means that a new SCSS module file was not successfully generated in this conversion, and then directly generate the new TSX file; if it exists, it is necessary to generate a reference code statement "import styles from '. / xxx.module.scss';" for the previously generated SCSS module file, and insert this statement at the very front of the script code. Subsequently, use the built-in file creation and writing API of the running environment to write this script code to the newly created xxx.tsx file in the same directory as the original file. If the file writing fails, this application will normally execute the subsequent steps and output a warning message in the console terminal: "The new TSX file: {xxx.tsx} creation failed"; if the file writing is successful, it marks the successful completion of this round of traversal, and output a prompt message in the console terminal: "The new TSX file: {xxx.tsx} creation successful", and continue to execute the next round of traversal.
[0223] After successfully completing the code conversion process, the command-line tool described in this application will output information indicating successful conversion in the command-line terminal, and then call the built-in API of the running environment to exit the script and return the corresponding exit code (usually 0, indicating success).
[0224] The front-end code automatic conversion method based on the command-line interface provided by this application can efficiently and accurately convert Vue files into TSX files and their corresponding dependent SCSS module files.
[0225] By comprehensively using libraries such as @babel, @vue / compiler-dom, postcss, postcss-scss, postcss-selector-parser, and sass, this application has achieved multiple innovations and optimizations in the technical solution, bringing the following beneficial effects:
[0226] 1) Efficient file parsing and conversion:
[0227] Automated processing: This application realizes the automated parsing and conversion of Vue files through a command-line tool, reducing manual intervention and improving the conversion efficiency.
[0228] Parsing Precision: With the help of tools such as @vue / compiler-dom and TypeScript, this application can accurately parse the template, script, and style parts in Vue files, generate a high-precision Abstract Syntax Tree (AST) representation, and provide a solid foundation for subsequent conversions.
[0229] Efficient Conversion: By converting Vue code represented by AST into JSX, TypeScript, and SCSS code that meets the requirements of TSX files, this application realizes an efficient code conversion process, ensuring the consistency of the converted code in terms of functionality, logic, and style.
[0230] 2) Support for SCSS Style Blocks and Deep Selectors:
[0231] SCSS Support: This application can handle SCSS style blocks in Vue files, retain and convert features such as variables, nested rules, and mixins, ensuring that the styles can be correctly applied in the converted environment.
[0232] Deep Selector Handling: This application can identify and handle the ::v-deep pseudo-class allowed in Vue files and convert it into the :global pseudo-class supported by SCSS files, thereby maintaining the scope and deep selector features of the styles and ensuring that the styles are correctly applied in the converted TSX files.
[0233] 3) Simple and Easy-to-Use Command-Line Tool:
[0234] This application provides a simple and easy-to-use command-line tool. Users can quickly execute the conversion of Vue files through simple commands and parameter configurations. The tool supports various configuration options, such as file paths and customizing the conversion process, to flexibly adapt to the needs of different projects.
[0235] 4) Improve Development Efficiency and Project Quality:
[0236] Through the automated tool, the seamless conversion of Vue files to TSX files is achieved, greatly reducing the workload and time cost of manual conversion and significantly improving development efficiency.
[0237] In summary, this application realizes the efficient conversion of Vue files to TSX files through an automated tool, bringing significant beneficial effects, including efficient file parsing and conversion, powerful code optimization, a simple and easy-to-use command-line tool, etc. It provides a powerful and flexible tool for developers to help them smoothly migrate existing Vue projects to projects using TypeScript and TSX syntax, thereby enhancing the overall quality and development experience of the project.
[0238] The automated conversion tool of this application is applicable to the following technology stacks and project types:
[0239] Vue (v2) single-file components (SFCs).
[0240] Projects using SCSS as a style preprocessor.
[0241] Projects that need to convert Vue files to TypeScript and TSX files.
[0242] In an exemplary embodiment, this application also provides a computer device, including: a memory, a processor, and a computer program stored on the memory and executable on the processor, where the processor executes the computer program to implement the above-mentioned front-end code automatic conversion method based on the command-line interface.
[0243] In an exemplary embodiment, this application also provides a computer-readable storage medium, on which a computer program is stored, and when the computer program is executed by a processor, it implements the above-mentioned front-end code automatic conversion method based on the command-line interface.
[0244] In an exemplary embodiment, this application also provides a computer program product, including a computer program, and when the computer program is executed by a processor, it implements the above-mentioned front-end code automatic conversion method based on the command-line interface.
[0245] Specific examples are used in this article to elaborate on the principles and implementation manners of this application. The descriptions of the above embodiments are only used to help understand the method and its core idea of this application; at the same time, for those of ordinary skill in the art, according to the idea of this application, there will be changes in the specific implementation manners and application scopes. In summary, the content of this specification should not be construed as a limitation to this application.
Claims
1. A method for automatically converting front-end code based on a command-line interface, characterized in that, The front-end code automatic conversion method based on the 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 for specifying the configuration file, the path instruction for specifying the file to be processed, and the stage instruction for specifying the stage to be processed; among them, 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, use the parseComponent API to parse out the script code snippet, template code snippet, and style code snippet in the Vue file; Based on the TypeScript class components in the TypeScript tool library, use the script code converter to perform code conversion on the script code snippet to generate the converted script code snippet; Based on the @vue / compiler-dom tool library and the @babel tool library, use the template code converter to perform code conversion on the template code snippet to generate the converted template code snippet; Based on the PostCSS tool library and the PostCSS-SCSS plugin, use the style code converter to perform code conversion on the style code snippet to generate the converted style code snippet; the style code converter is an SCSS preprocessor; Fuse and process the converted template code snippet and the converted style code snippet, and convert the fused code snippet and the converted script code snippet into a new code file; the new code file includes a TSX file and an SCSS module file, where 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 the configuration file path parameter, the list of file paths to be converted parameter, and the mandatory code conversion stage parameter.
2. The method for automatically converting front-end code based on a command-line interface according to claim 1, wherein Based on the command-line tool, according to the command-line parameters input by the user, using the parseComponent API to parse out the script code snippet, template code snippet, and style code snippet in the Vue file, there also includes a configuration file path parameter verification process, a list of file paths to be converted parameter verification process, and a mandatory code conversion stage parameter verification process; 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", "Failed to read configuration file content", or "Configuration file content is empty"; If the configuration file path exists and the configuration content in the configuration file path file is successfully read, temporarily store the read configuration content in a global variable to complete the verification process of the configuration file path parameter; If the user neither specifies the configuration file path parameter in the command line nor configures the USER_DEFINED_CONFIG_PATH environment variable in the running environment, in the current working directory where the user executes the command line, automatically call the built-in file creation API and file writing API of the code running environment 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 successfully written, repeat the above configuration file path parameter verification process; If the configuration file writing fails, terminate the process and output the error message "Failed to write configuration file" in the terminal; The verification process of the list parameter of the file path to be converted is as follows: If the user does not specify the list parameter of the file path to be converted, directly terminate the process and output the error message "No file to be processed" in the terminal; If the user specifies the list parameter of the file path to be converted, use the built-in API of the running environment to cut the parameter value of the string type, and the cutting point is the English half-width comma, and obtain a list of file paths; Traverse the list of file paths, process the leading and trailing spaces of each 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 and processing, 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, continue to execute the next process and output the warning message "There are illegal paths: {Path A}|{Path B}|..." in the terminal; If all are legal Vue file paths, normally continue to execute the next process; Temporarily store the list of verified legal file paths to be converted in a global variable; The verification process of the parameters in the mandatory processing stage of code conversion is as follows: If the user does not specify the parameters in the mandatory processing stage of code conversion, directly skip the verification process of the parameters in the mandatory processing stage of code conversion, and in the subsequent conversion process, perform full-stage conversion, and store the full-stage list ["style", "script", "template"] in a global variable; If the user specifies the parameters in the mandatory processing stage of code conversion, use the built-in API of the running environment to cut the parameter value of the string type, and the cutting point is the English half-width comma, and obtain a list of stages; 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, 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, continue to execute the next process and output the warning message "Illegal stages will be ignored: {Path A}|{Path B}|..." in the terminal; If all are legal stages, normally continue to execute the next process; Temporarily store the list of stages verified as legal in a global variable.
3. The front-end code automatic conversion method based on the command-line interface according to claim 1, characterized in that Based on the TypeScript class component of the TypeScript tool library, use the script code converter to perform code conversion on the script code snippet to generate the converted script code snippet, specifically including: Use the createSourceFile API in the TypeScript class component of the TypeScript tool library to parse the script code snippet to determine the script AST; the script AST includes all syntax nodes in the Vue file, and the syntax nodes include data, methods, computed 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 script AST in breadth-first traversal order to determine the type of each syntax node; Parse syntax nodes of different types to construct a new script AST; Based on the new script AST, call the printFile API in the TypeScript tool library to generate the converted script code snippet.
4. The method for automatically converting front-end code based on a command-line interface according to claim 3, characterized in that Parse syntax nodes of different types to construct a new script AST, specifically including: If the currently traversed syntax node is a PropertyAssignment node and the name identifier string of this PropertyAssignment node is "name", then take out and temporarily store the node initialization value corresponding to this PropertyAssignment node 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 this PropertyAssignment node is "data", and the initialization value node of this PropertyAssignment node is a method node, parse out the PropertyAssignment node corresponding to the return statement of this method node, and perform a recursive traversal on this PropertyAssignment node to parse out the first object property-value pair list; Call the typescript createPropertyDeclaration API to generate new first-class property nodes for each element in the first object property-value pair list, as part of the subsequent new jsx AST; If the currently traversed syntax node is a MethodDeclaration node, and the name identifier string of this MethodDeclaration node is "data", parse out the MethodDeclaration node corresponding to the return statement of this MethodDeclaration node, and perform a recursive traversal on this MethodDeclaration node to parse out the second object property-value pair list from it; Call the typescript createPropertyDeclaration API to generate new second-class property nodes 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 this PropertyAssignment node is one of "components", "filters", or "directives", then temporarily store this PropertyAssignment node respectively for subsequent reuse as part of the new jsx AST; If the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of this PropertyAssignment node is "computed", and the initialization value node of this PropertyAssignment node is an object type node, then recursively traverse the object AST node to parse out the property names, property calculation methods, and property accessor types corresponding to each computed property from it; Call the createGetAccessorDeclaration method or the createSetAccessorDeclaration method to generate new class accessor property nodes corresponding to the computed properties, as part of the subsequent new jsx AST; If the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of this PropertyAssignment node is "methods", and the initialization value node of this PropertyAssignment node is an object type node, then recursively traverse this object AST node to parse out the method names, method input parameters, function bodies, and modifiers corresponding to each component method; Call the createMethodDeclaration method to generate a new class method node corresponding to the component method, which is part of the subsequent new jsxAST; If the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of this PropertyAssignment node is "props", and the initialization value node of this PropertyAssignment node is an object type node, then recursively traverse this object AST node to parse out the prop identifier names and prop initialization values corresponding to each component prop; Call the createPropertyDeclaration method to generate a new first-class property declaration node corresponding to the component prop, which is part of the subsequent new jsxAST; If the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of this PropertyAssignment node is "props", and the initialization value node of this PropertyAssignment node is an array type node, then traverse the array AST node and call the createPropertyDeclaration method for each array element to generate a new second-class property declaration node corresponding to the component prop, which is part of the subsequent new jsxAST; If the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of this PropertyAssignment node is "watch", and the initialization value node of this PropertyAssignment node is an object type node, then recursively traverse the object AST node to parse out the watcher identifier names, watcher method parameters, watcher method bodies, watcher objects, and watcher configurations corresponding to each component watcher; Call the createMethodDeclaration method to generate a new class method declaration node corresponding to the component watcher, which is part of the subsequent new jsxAST; If the currently traversed syntax node is a PropertyAssignment node, and the name identifier string of this PropertyAssignment node is any one of "beforeCreate", "created", "beforeMount", "mounted", "beforeUpdate", "updated", "activated", "deactivated", "beforeDestroy", "destroyed", and "errorCaptured", it indicates that the current node is a Vue component lifecycle hook node. Parse the identifier name, method parameters, method body, and identifier corresponding to the lifecycle method from this 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, which is part of the subsequent new jsxAST; If the currently traversed syntax node is an ExportAssignment node, it indicates that the current node is a default export node. Perform a full recursive traversal of the expression child node of this default export node and skip processing this default export node; If the currently traversed syntax node is an unprocessed node, there is no need to perform a recursive traversal. Only temporarily store this unprocessed node for later use as part of the new jsxAST. The unprocessed nodes are ImportDeclaration nodes, ExportDeclaration nodes, or VariableStatement nodes; Construct a new scriptAST based on the component name of the new jsx code snippet and a part of the new jsxAST.
5. The method for automatically converting front-end code based on a command-line interface according to claim 1, characterized in that Based on the @vue / compiler-dom tool library and the @babel tool library, use the template code converter to perform code conversion on the template code snippet, generating a converted template code snippet, specifically including: Use the parseAPI of the @vue / compiler-dom tool library to parse the template code snippet to obtain a templateAST. The templateAST includes all types of nodes in the component template. The types of nodes include tag nodes, text nodes, directive nodes, and component nodes; Traverse the templateAST in a depth-first recursive order, combined with conditional control statements, perform different parsing and processing for different types of marked nodes, and construct 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.
6. The method for automatically converting front-end code based on a command-line interface according to claim 5, characterized in that Traverse the templateAST in a depth-first recursive order, and combine conditional control statements to perform different parsing and processing for different types of token nodes. Based on the API of the @babel tool library, construct a new jsxAST, specifically including: If the currently traversed token node is an ELEMENT node, determine the props attribute in the ELEMENT node; the props attribute includes all the attribute node lists in the ELEMENT node; Combine conditional control statements to classify each attribute node in the attribute node list to determine the attribute information list; Traverse the attribute information list and generate new jsxAST attribute nodes corresponding to each element in the attribute information list; If the currently traversed token 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 nodes of each child node and the instruction type attribute to be processed; Traverse the child node list in ascending order to process the for loop instruction, call the parseExpression API to convert the attribute value string into a loop expression AST, and parse out the loop object and loop parameters from it. Then, use the jsxExpressionContainer of the @babel tool library in combination with multiple APIs to construct an AST node corresponding to the code in the form of "{xxx.map(y => {return child node})}"; the multiple APIs include callExpression, arrowFunctionExpression, and blockStatement; where xxx.map is the loop statement and y is the loop parameter; Traverse the child node list in descending order, group the child nodes with conditional pairing relationships, and for the child nodes included 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 node1 : child node2}"; where "{a? child node1 : child node2}" is the 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 an html native tag name; if so, do nothing, if not, then regard the ELEMENT node as a component node and format the name of the tag attribute in camelCase; Call the jsxElementAPI and pass in the processed tag attribute name, the processed attribute node list, and the processed child node list as parameters to generate a new jsx node; If the currently traversed token node is a TEXT node, call the 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 the parseExpression API to parse the INTERPOLATION node into an expression AST, and finally call the jSXExpressionContainer API to generate a new jsx node for the INTERPOLATION node; Based on the APIs of the @babel tool library, construct a new jsx AST according to all the new jsx nodes.
7. The method for automatically converting front-end code based on a command-line interface according to claim 1, wherein Based on the PostCSS tool library and the PostCSS-SCSS plugin, use the style code converter to perform code conversion on the style code snippet to generate a converted style code snippet; The style code converter is an SCSS preprocessor, specifically including: Use the PostCSS tool library and the PostCSS-SCSS plugin to parse the style code snippet to determine the style AST; Use the walkRules API in the PostCSS tool library to traverse the nodes in the style AST, and replace the ::v-deep pseudo-class in the style AST with the :global pseudo-class to construct a new style AST; Based on the new style AST, call the process API provided by the PostCSS tool library to generate a converted style code snippet.
8. The method for automatically converting front-end code based on a command-line interface according to claim 1, wherein Use the walkRules API in the PostCSS tool library to traverse the nodes in the style AST, and replace the ::v-deep pseudo-class in the style AST with the :global pseudo-class to construct a new style AST, specifically including: Determine whether the currently traversed node is a node of the rule type; If the currently traversed node is a node of the rule type, use the processSync of the PostCSS tool library to recursively traverse the pseudo-class selectors included in the selector field selector of the node in cooperation with the selectorParser and the walkPseudos API; 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 use this pseudo-class node as the target pseudo-class to be processed by the converter, and call the selectorParser.pseudo API in cooperation with the replaceWith API 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 this pseudo-class node; If the currently traversed node is not a node of the rule type, then ignore this node; Until all nodes in the style AST are traversed, construct a new style AST.
9. The method for automatically converting front-end code based on a command-line interface according to claim 8, wherein Based on the new style AST, call the process API provided by the PostCSS tool library to generate the transformed style code snippet. Subsequently, it also includes: Call the walkRules API of PostCSS to traverse the rule nodes of the new style AST; Traverse the selectors list of the rule node, and for each list element in the selectors list, call postcssSelectorParser in conjunction with the processSync API 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 the walk API to traverse the selector list to obtain the global class name list.
10. The method for automatically converting front-end code based on a command-line interface according to claim 2, wherein Fuse and process the transformed template code snippet and the transformed style code snippet, and convert the fused code snippet and the transformed script code snippet into a new code file, specifically including: Obtain the original Vue file name through the built-in API of the running environment; Determine whether there is a "style" phase in the phase list; if so, write the transformed style code snippet to a 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 running environment; if the file writing fails, execute the next process normally and output a warning message in the console terminal: "Failed to create new SCSS module file: {xxx.module.scss}"; if the file writing is successful, output a prompt message in the console terminal: "New SCSS module file: {xxx.module.scss} created successfully", and temporarily store the SCSS module file name in a local variable; if not, skip the "style" phase; Determine whether there is a "template" phase in the phase list; if not, directly skip the "template" phase and continue with the subsequent steps based on the transformed script code snippet; if so, determine whether there is a "script" phase in the phase list; if there is a "script" phase, call the built-in string replacement API of the running environment to replace the placeholder string "==========jsx here==========" set in the transformed script code snippet with the new jsx code snippet, and continue with the subsequent steps using the replaced script code snippet; if there is no "script" phase in the phase list, embed a simple version of the script code and use the same placeholder string "==========jsx here==========" at the position where jsx is required for embedding; If both the "template" phase and the "script" phase exist in the phase list, generate a new TSX file for the converted script code snippet; the new file name of the new TSX file is obtained by converting the original Vue file name to camelCase and appending the.tsx suffix. Before writing to the file, check if the local variable of the new SCSS module file name has a value; if it has no value, it means that the new SCSS module file was not successfully generated during this conversion, and then directly generate the new TSX file; if it has a value, generate a reference code statement for the new SCSS module file and insert this reference code statement at the very front of the script code snippet. Use the built-in file creation and writing API of the running environment to write this script code snippet to a newly created xxx.tsx file in the same directory as the original Vue file; if the file writing fails, execute the subsequent steps normally and output a warning message in the console terminal: "Failed to create new TSX file: {xxx.tsx}"; if the file writing is successful, it indicates that this round of traversal has been successfully completed, output a prompt message in the console terminal: "New TSX file: {xxx.tsx} created successfully", generate the new code file, and continue to execute the next round of traversal.
11. A computer device, comprising: A memory, a processor, and a computer program stored on 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 according to any one of claims 1-10.
12. A computer-readable storage medium having a computer program stored thereon, characterized in that, When the computer program is executed by the processor, it implements the command-line interface-based front-end code automatic conversion method according to any one of claims 1-10.
13. A computer program product, comprising a computer program, characterized in that, When the computer program is executed by the processor, it implements the command-line interface-based front-end code automatic conversion method according to any one of claims 1-10.
Citation Information
Patent Citations
Vue file conversion method and device, electronic equipment and storage medium
CN113360141A
System and method for reflection-based integrated code and design editing
US20240303049A1