Method and system for dynamically loading SCSS file based on webpack loader
By passing a version number parameter during the webpack build process and using a custom loader to dynamically load SCSS files, the problems of code redundancy and Git conflicts in multi-version component development are solved. This enables multi-version style switching and online traceability with zero manual operation, improving development efficiency and build speed.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-01-13
- Publication Date
- 2026-04-17
AI Technical Summary
Existing technologies suffer from code redundancy, frequent Git conflicts, runtime splashing, and poor SSR compatibility in handling component-based front-end development across multiple online versions. They also lack dynamic style loading solutions that require zero manual intervention and have zero runtime costs.
By passing the version number parameter of the target component to the webpack build startup command, a custom loader is used to dynamically generate the absolute path of the SCSS file and append it to the component source code during compilation. This leverages caching optimization and parallel compilation techniques to achieve dynamic loading and source tracing of multiple version styles.
It enables dynamic loading and switching of multiple styles with zero manual intervention during compilation, reducing code redundancy and Git conflict risks, improving development efficiency, and supporting second-level traceability of online versions.
Smart Images

Figure CN121879866A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of front-end engineering construction technology, and in particular to a method and system for dynamically loading SCSS files based on webpack loader. Background Technology
[0002] As front-end components become increasingly modular, multiple online versions of the same business component often coexist. While the DOM structure is highly consistent across versions, the styles differ significantly. Traditional practices include:
[0003] Manually copying component directories and modifying import paths leads to code redundancy and frequent Git conflicts;
[0004] Dynamically switching CSS via JavaScript at runtime causes issues such as screen flickering, additional network requests, and poor compatibility with server-side rendering (SSR).
[0005] Therefore, there is an urgent need for a dynamic style loading solution that requires zero manual intervention during compilation, has zero runtime cost, can be accelerated in parallel, and supports online version traceability. Summary of the Invention
[0006] The purpose of this invention is to provide a method and system for dynamically loading SCSS files based on webpack loader, thereby solving the aforementioned problems existing in the prior art.
[0007] To achieve the above objectives, the technical solution adopted by the present invention is as follows:
[0008] A method for dynamically loading SCSS files based on webpack loader includes the following steps:
[0009] a) Pass the version number parameter of the target component in the webpack build startup command;
[0010] b) Create a custom webpack loader that takes the source code string of the component to be processed as input;
[0011] c) Parse the component's metadata inside the custom loader, and dynamically generate the absolute path of the SCSS file corresponding to the version of the component based on the predetermined path rules and version number parameters;
[0012] d) Append the SCSS file path to the end of the component's source code string using an import statement to obtain the updated source code string;
[0013] e) Return the updated source code string to the webpack process so that sass-loader and css-loader can complete the compilation and injection of this version of the SCSS file;
[0014] f) Finally, the output of the build process yields a component module with only the required version styles, enabling dynamic switching of multiple style sheets within the same DOM structure and zero manual import.
[0015] Preferably, the version number parameter is hashed using SHA-256 to obtain a verification digest before injection.
[0016] The custom loader recalculates the digest after reading the version number and compares it with the verification digest.
[0017] If discrepancies are found, immediately terminate the build process and report the version tampering error.
[0018] Preferably, after the custom loader parses the component metadata for the first time,
[0019] The parsing results are serialized into binary blobs and written to both the memory LRU cache and the disk cache directory.
[0020] When a subsequent build hits the same component again, it will first read from the memory cache; otherwise, it will read from the disk cache.
[0021] This skips repetitive AST parsing, reducing overall construction time by more than 20%.
[0022] Preferably, when dynamically generating absolute paths,
[0023] First, use the semver library to perform range matching on all version directories existing in the file system.
[0024] If a match fails, fall back to the latest symbolic link.
[0025] Only throw an error if it still fails;
[0026] This supports the "fuzzy version" command, reducing the number of releases.
[0027] Preferably, before adding the import statement,
[0028] First, use @babel / parser to generate the AST.
[0029] Traverse the ImportDeclaration nodes and calculate the absolute path fingerprint of existing paths.
[0030] If the fingerprint matches the path to be appended, skip it;
[0031] At the same time, complete incremental modification through magic-string to ensure that the line and column numbers of the source-map do not drift.
[0032] Preferably, before returning the updated source code string,
[0033] synchronously append the absolute path of SCSS to the compilation.fileDependencies of webpack,
[0034] and set loaderContext.cacheable(false) to trigger parallel sass-loader instances,
[0035] so as to utilize multiple-core CPUs to compile multiple versions of styles simultaneously and shorten the total build time.
[0036] Preferably, in the build output stage,
[0037] append to the head of each CSS module through the additionalData option of css-loader
[0038] / * Version:<version number> GitHash:<current commit hash> BuildTime:<ISO time> * / comment, which can be read and reported through
[0039] document.styleSheets[n].ownerNode.textContent during the real-time browser operation,
[0040] to achieve second-level traceability of the online style version.
[0041] Preferably, the predefined path rule is:
[0042] The root directory of the project / src / styles / component name / {version number} / index.scss;
[0043] The custom loader is registered to the webpack module parsing process through the chainWebpack configuration item in vue.config.js and is limited to act only on *.vue files.
[0044] Furthermore, a webpack build system includes:
[0045] A version number injection module for performing the above step a);
[0046] A custom loader module for performing the above steps b)-e);
[0047] The parallel sass-loader scheduling module is used to perform the parallel compilation described above;
[0048] And the webpack core compilation module, which is used to package and output components and corresponding versions of SCSS files.
[0049] Furthermore, a computer-readable storage medium having a computer program stored thereon, which, when executed by a processor, implements the steps of the above method.
[0050] Also includes: electronic devices,
[0051] Electronic devices include a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor executes the program to implement the methods described above.
[0052] The beneficial effects of this invention are:
[0053] This solution uses a custom webpack loader to dynamically import the corresponding version of the stylesheet into the component via command-line arguments, without affecting the original content of the component. This avoids Git version management issues when multiple developers are working simultaneously, reduces the probability of errors caused by manual copying, and allows developers to focus solely on stylesheet version maintenance without worrying about the component importing stylesheets. Furthermore, the development of multiple component versions does not interfere with each other, thus improving development efficiency. Attached Figure Description
[0054] Figure 1 This is a flowchart of the method of the present invention;
[0055] Figure 2 This is a flowchart of the webpack build process of the present invention. Detailed Implementation
[0056] To make the objectives, technical solutions, and advantages of this invention clearer, the invention will be further described in detail below with reference to the accompanying drawings. It should be understood that the specific embodiments described herein are merely illustrative and not intended to limit the invention.
[0057] Reference Figure 1 and Figure 2 The method shown here for dynamically loading SCSS files based on webpack loader includes the following steps:
[0058] a) Pass the version number parameter of the target component in the webpack build startup command;
[0059] Before the webpack build process officially starts, operators inject the version number of the target component as a parameter into the entire build environment via the command-line interface. Specifically, this parameter is written into the startup command as an environment variable and then passed to the webpack configuration context by tools such as cross-env, becoming shared information that can be read by each subsequent build stage. Since the environment variable is injected once with the command, no hard-coded modifications to the project source code are required, achieving a flexible "one command, one version" correspondence. At the same time, this parameter is locked at the operating system process level, and any spelling errors or malicious tampering of the version value will be detected and blocked in time during subsequent verification, thus ensuring the determinism and security of the build result. In this way, the version number, as the starting point of the entire dynamic loading chain, is non-intrusively introduced into the webpack compilation lifecycle, laying the foundation for subsequent automatic matching of the corresponding style files.
[0060] b) Create a custom webpack loader that takes the source code string of the component to be processed as input;
[0061] In webpack's module parsing pipeline, this step introduces a custom-designed loader, whose role is defined as a "version style injector." This loader is registered with the webpack configuration as a regular JavaScript module. When the compilation process encounters a target component file, webpack will pass it to this loader for processing according to the configuration order. The loader's only input is the complete source code string of the component module, containing all fragments such as templates, scripts, and style declarations. At this stage, the source code has not been touched by any subsequent transpilation tools, so the loader can obtain and analyze the component structure at the most primitive literal level. Internally, the loader first identifies the component name corresponding to the current file, then reads the version number parameter injected in the previous step from the process environment, and locates the style entry file uniquely corresponding to the component and version in the file system according to pre-agreed directory rules. After locating, the loader appends a new import statement to the end of the source code string in memory, forming the updated module content, and immediately returns this content to the webpack pipeline, thus completing a "non-intrusive, zero-copy" version style injection operation. Throughout the process, the loader only operates at the string level and does not involve runtime behavior, so it will not produce any side effects on the existing logic of the source code, and at the same time, it preserves a clean input foundation for various subsequent translation tools.
[0062] c) Parse the component's metadata inside the custom loader, and dynamically generate the absolute path of the SCSS file corresponding to the version of the component based on the predetermined path rules and version number parameters;
[0063] After obtaining the source code string, the custom loader first performs a lightweight parsing to extract key metadata representing the component's identity—usually the folder name of the directory containing the file, which can also be confirmed by reading attribute comments or filename fragments within the single-file component. Once the component name is obtained, the loader immediately retrieves the previously injected version number parameter from the current process's environment variables and substitutes both into a pre-defined directory paradigm: within the style root directory under the project source code area, a subdirectory named after each component is maintained, and within each subdirectory, the version number is used as the next-level folder name, ultimately pointing to a unique index style file. Using the file system path concatenation mechanism, the loader constructs the absolute path to the index file in memory in real time and immediately performs an existence check; if the path is invalid, the build is interrupted with a clear warning; if the path is valid, the absolute path is retained for subsequent injection. Thus, a one-to-one deterministic mapping is formed between the component, version, and style file. The entire parsing and location process occurs entirely during the compilation phase, requiring no manual intervention or modification of existing component source code, providing a precise and secure address basis for the next step of source-level injection.
[0064] d) Append the SCSS file path to the end of the component's source code string using an import statement to obtain the updated source code string;
[0065] After the path is located within the custom loader, the resulting absolute path is immediately encapsulated into a standard style import statement in memory. This statement follows the project's established module syntax specifications, appears as a static import, and its suffix explicitly points to the Cascading Style Sheets (CSS) file. To ensure that the import action does not conflict with existing similar statements in the source code, the loader first performs a syntax scan of the original string: if the same target path is already referenced, it is skipped; if not, the new statement is appended to the end of the source code string while maintaining the original line number structure, forming an updated complete module content. The entire appending process involves only incremental modifications at the string level, without disrupting the original script logic of the component or affecting the alignment of the template area, while preserving all the positional information required by subsequent transpilation tools. After writing is complete, the loader immediately returns this new string, now carrying version style dependencies, to the webpack pipeline, enabling the downstream sass-loader and css-loader to recognize and process this new dependency without being aware of it, thus presenting only the style definitions corresponding to the target version in the final output.
[0066] e) Return the updated source code string to the webpack process so that sass-loader and css-loader can complete the compilation and injection of this version of the SCSS file;
[0067] After the loader completes the path appending, it immediately returns the new source code string to webpack's module processing context. At this point, the component source code already contains a dependency statement pointing to a specific version of the stylesheet file. Webpack's dependency resolution system recognizes this path as a new resource request and reroutes it according to established rules. Subsequently, sass-loader receives this request, performs syntax transpilation and variable calculation on the corresponding Cascading Style Sheets (CSS) file, and the resulting intermediate results are then module-encapsulated and style-extracted by css-loader, finally merging them into the exported module of the same component. Because the entire dependency chain is statically established during the compilation phase, all style content is written into the artifacts at once during the bundled output, no longer relying on additional runtime requests or script injections, thus achieving zero runtime overhead version style switching. Through this process, webpack completes the compilation, optimization, and injection of the target version style in a transparent and efficient manner, ensuring that the build result is strictly consistent with the version number passed in from the command line.
[0068] f) Finally, the output of the build process yields a component module with only the required version styles, enabling dynamic switching of multiple style sheets within the same DOM structure and zero manual import.
[0069] Once the webpack pipeline has completed the compilation and bundling of all dependencies, the final output only retains the style content corresponding to the command-line version number; the DOM structure of the components remains unchanged and is neither copied nor modified. At this point, the same template and logic code can generate multiple independent resource bundles with a single build command. Each resource bundle contains style definitions for a specific version, and no dynamic scripts or additional requests are required when loading on the browser side, achieving "zero runtime" difference rendering. Because the style injection process is entirely automated by the loader during compilation, developers do not need to manually rewrite the import path or maintain independent component copies for each version, thus completely eliminating the risks of manual copying, duplicate code, and Git conflicts inherent in traditional solutions. With this mechanism, projects can achieve parallel delivery of multiple versions with minimal maintenance costs, truly achieving instant switching and seamless import of multiple stylesheet versions under the same DOM structure.
[0070] Preferably, the version number parameter is hashed using SHA-256 to obtain a verification digest before injection.
[0071] The custom loader recalculates the digest after reading the version number and compares it with the verification digest.
[0072] If discrepancies are found, immediately terminate the build process and report the version tampering error.
[0073] While the version number parameter is written to the startup command, the build system first performs an irreversible hash operation on the string, generating a fixed-length digest value, which is then passed to the webpack environment as a verification credential along with the process variable. After obtaining the version number, the custom loader immediately re-executes the same hash calculation on the current value to obtain a new digest, and compares it bit by bit with the previously passed credential. If they match perfectly, it means the version number has not been tampered with or miswritten during transmission, and the loader continues the subsequent process. If a discrepancy is found, it is determined to be a potential human spelling error, malicious injection, or environment variable overwriting. The loader immediately interrupts the entire build task, outputs a clear version tampering error message to the console, and notifies the upstream continuous integration platform to terminate the deployment. Through this mechanism, the version number is upgraded from a regular input string to a security token with self-verification capabilities, ensuring that all subsequent path resolution and style injection are based on a trusted and unique foundation, thereby avoiding style misalignment or online failures caused by version errors.
[0074] Preferably, after the custom loader parses the component metadata for the first time,
[0075] The parsing results are serialized into binary blobs and written to both the memory LRU cache and the disk cache directory.
[0076] When a subsequent build hits the same component again, it will first read from the memory cache; otherwise, it will read from the disk cache.
[0077] This skips repetitive AST parsing, reducing overall construction time by more than 20%.
[0078] When a custom loader encounters a component for the first time, it serializes its metadata—such as component name, path, and version key-value pairs—into a compact binary object. This object is written to two layers of cache: the top layer is an LRU structure in memory, which can be quickly read and written throughout the build process; the bottom layer is a persistent directory on disk, retained across processes and builds. If the same component re-enters the loader, it first performs a key-value match test in memory. If it exists, it is retrieved directly, and AST parsing is skipped; if it misses a memory cache, it reads from the disk cache, and if it still matches, it is refilled into memory and used again. Only when neither cache layer exists does the loader re-execute the complete parsing process. This significantly reduces the number of times the same component is accessed during repeated builds, significantly reduces CPU usage, and lowers overall build time by more than 20%. Furthermore, the cache files are independent of the source code repository, allowing for flexible and controllable cleanup or migration.
[0079] Preferably, when dynamically generating absolute paths,
[0080] First, use the semver library to perform range matching on all version directories existing in the file system.
[0081] If a match fails, fall back to the latest symbolic link.
[0082] Only throw an error if it still fails;
[0083] This supports the "fuzzy version" command, reducing the number of releases.
[0084] During the stage of dynamically constructing the absolute path of the style file, the custom loader does not require the command line to provide an exact version number. Instead, it uses semantic versioning rules to intelligently match the range of all existing version directories in the file system. Specifically, the loader first treats the names of each version folder under the component directory as semantic version numbers, forming a local version set. Then, it uses the passed version parameter as a range expression to search for the optimal version that meets the conditions within this set. If the range match is successful, the matching version is immediately used to continue the subsequent process; if not, it further checks whether the component directory maintains a symbolic link named "latest," which usually points to the latest stable version, and the loader uses this as a fallback option. Only when both range matching and symbolic link fallback fail will the build be actively interrupted and a clear version missing error be thrown. Through this progressive strategy, developers only need to enter a vague version such as "^1.2.0" or "~1.0" in daily iterations to automatically locate the highest compatible patch or minor version, without having to update the build command for each release, thus significantly reducing the number of releases and improving continuous integration efficiency.
[0085] Preferably, before adding the import statement,
[0086] First, use @babel / parser to generate the AST.
[0087] Traverse the ImportDeclaration nodes and calculate the absolute path fingerprint of existing paths.
[0088] If the fingerprint matches the path to be appended, skip it;
[0089] Meanwhile, incremental modifications are performed using magic-string to ensure that the row and column numbers of the source-map do not drift.
[0090] Before writing the style file path into the component source code, the custom loader first feeds the entire source code string into the syntax parser, generating a complete abstract syntax tree. Then, the loader traverses all import declaration nodes in the tree, extracting the target path pointed to by each import statement and resolving the corresponding absolute path fingerprint using the file system. If a fingerprint completely matches the path to be appended, it means that the style version has already been referenced, and the append operation will be skipped immediately to avoid style overwriting or file size bloat caused by duplicate imports. When appending is confirmed, the loader uses an incremental update tool to perform local insertion in the source code: this tool only modifies the specified position of the string and synchronously adjusts the source code mapping relationship, ensuring that the row and column information in subsequent compilation artifacts always correspond to the original file. Therefore, the line and column numbers seen by developers during debugging or error location will not be offset, ensuring both the accuracy of the import statements and maintaining a consistent debugging experience.
[0091] Preferably, before returning the updated source code string,
[0092] Simultaneously append the absolute path of the SCSS to webpack's compilation.fileDependencies.
[0093] And set loaderContext.cacheable(false) to trigger a parallel sass-loader instance.
[0094] This allows for the simultaneous compilation of multiple styles using a multi-core CPU, thus shortening the overall build time.
[0095] After appending the source code and before handing the results back to webpack, the loader immediately registers the absolute path of the newly generated SCSS in the dependency list for the current build cycle. This operation makes webpack internally aware that "version styles" are independent resources that must be tracked in this build, thus assigning them independent build subtasks. Subsequently, the loader actively declares itself as non-cached through cache control flags, forcing webpack to create a new loader instance chain for each version. At this time, sass-loader is simultaneously awakened in multiple worker processes under the action of the scheduler, each occupying different CPU cores, to perform parallel transpilation and optimization of style files belonging to the same batch but with different version numbers. Because disk I / O and CPU computation are distributed across multiple cores for parallel execution, the overall build time is significantly shortened, and the compilation results of each version style are kept isolated from each other through the internal dependency graph, ensuring that the final products do not contaminate each other or produce order errors.
[0096] Preferably, in the output construction stage,
[0097] Append to the head of each CSS module through the additionalData option of css-loader
[0098] / * Version:<version number> GitHash:<current commit hash> BuildTime:<ISO time> * / comment, which can be read and reported through
[0099] document.styleSheets[n].ownerNode.textContent at runtime,
[0100] Implement second-level traceability of online style versions.
[0101] In the final stage of the build output, the additional data option of css-loader is used to inject a comment in the standard format into the head of each CSS module. This comment sequentially records the currently passed version number, the hash value of the most recent Git commit, and the ISO standard time when the build is completed. The three are connected by a fixed delimiter to form a unique and readable triple identifier. Since the comment is at the very front of the style sheet, the browser will treat it as an ordinary text node and retain it in the style sheet object in memory after parsing. At runtime, the front-end monitoring script only needs to traverse the document.styleSheets collection, read the text content under any node, and can extract this identifier within milliseconds, and immediately report it to the operation and maintenance platform through the log channel. With this mechanism, once style differences or anomalies appear in the online environment, maintenance personnel can accurately locate the corresponding version, commit record, and build time within seconds without having to repackage or roll back the code, thus achieving rapid traceability and precise rollback.
[0102] Preferably, the predetermined path rule is:
[0103] The root directory of the project / src / styles / component name / {version number} / index.scss;
[0104] The custom loader is registered to the webpack module parsing process through the chainWebpack configuration item in vue.config.js and is limited to only act on *.vue files.
[0105] The project adopts a fixed directory structure: a separate root directory for styles is established under the source code area, subfolders are created by component name, and then the version number is used as the next level directory, ultimately pointing to the index file storing style entry points. Custom loaders construct absolute paths according to this rule, ensuring that the style entry points for different versions of the same component are always unique and predictable. To ensure that the loader only intervenes in the build process of single-file components, it is registered in the webpack module parsing rules in the project configuration using a chained approach, limiting its matching to files with the .vue extension. In this way, the loader is only triggered when processing component files, avoiding interference with ordinary scripts or style resources. Simultaneously, the chained configuration ensures that the execution order is before template compilation, allowing appended import statements to enter the subsequent translation stage along with the component source code, thus achieving precise, efficient, and side-effect-free version style injection.
[0106] Furthermore, a webpack build system includes:
[0107] The version number injection module is used to perform step a) above;
[0108] A custom loader module is used to perform steps b)-e) above;
[0109] The parallel sass-loader scheduling module is used to perform the parallel compilation described above;
[0110] And the webpack core compilation module, which is used to package and output components and corresponding versions of SCSS files.
[0111] This webpack build system consists of four collaborative modules: a version number injection module, which writes the target component version number into the process context as an environment variable during the build startup phase, providing a unique basis for subsequent path resolution; a custom loader module, chained in the webpack module resolution chain, sequentially extracts component metadata, dynamically concatenates version paths, performs AST-level deduplication, and appends import statements, achieving zero-manual style dependency injection; a parallel sass-loader scheduling module, by explicitly registering SCSS paths to the webpack dependency graph and triggering multi-instance scheduling, enables different versions of style files to be translated simultaneously on multi-core CPUs, significantly shortening the overall build time; and a webpack core compilation module, which coordinates the dependencies generated by each submodule, ultimately bundling and outputting component modules containing only the target version styles, thus enabling rapid switching and accurate source tracing of multiple stylesheet versions within the same DOM structure. Each module has a clear responsibility and is tightly integrated, forming a complete automated pipeline from version input to product delivery.
[0112] Furthermore, a computer-readable storage medium having a computer program stored thereon, which, when executed by a processor, implements the steps of the above method.
[0113] Also includes: electronic devices,
[0114] Electronic devices include a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor executes the program to implement the methods described above.
[0115] A computer-readable storage medium stores a non-transient sequence of compiled executable instructions. When a processor loads and runs this sequence, it sequentially completes all build steps, including version number injection, custom loader parsing, dynamic path generation, AST deduplication injection, parallel Sass compilation, and artifact comment appending. This outputs a component module containing only the target version style without human intervention. Correspondingly, the electronic device consists of a memory and a processor: the memory persistently stores the program and the component source code and style files required during the build process; the processor, upon receiving a build trigger signal, loads the program instructions into the runtime space and sequentially calls each functional module, achieving zero-runtime switching between multiple stylesheet versions under the same DOM structure, online second-level traceability, and a significant reduction in overall build time. This medium and device solution allows the invention to be deployed rapidly in various hardware environments, such as edge CI nodes, cloud containers, or local workstations, independent of specific development machines, demonstrating industrial-grade replicability and large-scale promotion value.
[0116] Example:
[0117] In the front-end engineering of a large car dealership platform, the same "Car Model Filtering" component needed to support simultaneous operation in 32 regional versions. The only difference between regions was the style; the DOM structure and business logic were completely consistent. After adopting this invention, the project team stored the regional styles according to the convention "src / styles / CarFilter / {version number} / index.scss" and injected the version parameter into the CI pipeline using the command "cross-env VERSION=1.8.7 npm run build".
[0118] During the compilation phase, the custom loader automatically resolves the component name "CarFilter", combines it with the version number to construct the absolute path, and then appends the corresponding style import statements to the end of the component source code. During the build process, the loader uses AST fingerprinting to avoid duplicate imports, and simultaneously triggers parallel sass-loader to compile the 1.8.7 version styles on multiple cores; the css-loader injects the comment " / *Version:1.8.7 GitHash:3f4a2c1 BuildTime:2025-06-20T14:23:42Z * / " into the header of the output.
[0119] The final output contains only component modules with the 1.8.7 region style, reducing the overall build time from 180 seconds to 105 seconds. In the online environment, version tracing can be completed within 3 seconds by reading comments. This embodiment has been running continuously for 12 months, with a 75% reduction in style-related failure rate, fully verifying the industrial applicability of the invention.
[0120] The beneficial effects of this invention are:
[0121] This solution uses a custom webpack loader to dynamically import the corresponding version of the stylesheet into the component via command-line arguments, without affecting the original content of the component. This avoids Git version management issues when multiple developers are working simultaneously, reduces the probability of errors caused by manual copying, and allows developers to focus solely on stylesheet version maintenance without worrying about the component importing stylesheets. Furthermore, the development of multiple component versions does not interfere with each other, thus improving development efficiency.
[0122] The above description is only a preferred embodiment of the present invention. It should be noted that for those skilled in the art, several improvements and modifications can be made without departing from the principle of the present invention, and these improvements and modifications should also be considered within the scope of protection of the present invention.
Claims
1. A method for dynamically loading SCSS files based on webpack loader, characterized in that, Includes the following steps: a) Pass the version number parameter of the target component in the webpack build startup command; b) Create a custom webpack loader that takes the source code string of the component to be processed as input; c) Parse the component's metadata within the custom loader, and dynamically generate the absolute path of the SCSS file corresponding to the version of the component based on the predetermined path rules and the version number parameter; d) Append the SCSS file path to the end of the component source code string using an import statement to obtain the updated source code string; e) Return the updated source code string to the webpack process so that sass-loader and css-loader can complete the compilation and injection of this version of the SCSS file; f) Finally, the output of the build process yields a component module with only the required version styles, enabling dynamic switching of multiple style sheets within the same DOM structure and zero manual import.
2. The method according to claim 1, characterized in that, The version number parameter is hashed using SHA-256 to obtain a verification digest before injection. The custom loader recalculates the digest after reading the version number and compares it with the verification digest. If discrepancies are found, immediately terminate the build process and report the version tampering error.
3. The method according to claim 1, characterized in that, After the custom loader parses the component metadata for the first time... The parsing results are serialized into binary blobs and written to both the memory LRU cache and the disk cache directory. When a subsequent build hits the same component again, it will first read from the memory cache; otherwise, it will read from the disk cache. This skips repetitive AST parsing, reducing overall construction time by more than 20%.
4. The method according to claim 1, characterized in that, When dynamically generating absolute paths First, use the semver library to perform range matching on all version directories existing in the file system. If a match fails, fall back to the latest symbolic link. Only throw an error if it still fails; This supports the "fuzzy version" command, reducing the number of releases.
5. The method according to claim 1, characterized in that, Before adding the import statement First, use @babel / parser to generate the AST. Traverse the ImportDeclaration nodes and calculate the absolute path fingerprint of existing paths. If the fingerprint matches the path to be appended, skip it; Meanwhile, incremental modifications are performed using magic-string to ensure that the row and column numbers of the source-map do not drift.
6. The method according to claim 1, characterized in that, Before returning the updated source code string. The absolute path of the SCSS is appended to webpack's compilation.fileDependencies. And set loaderContext.cacheable(false) to trigger a parallel sass-loader instance. Thus, the multi-core CPU is utilized to compile multiple version styles simultaneously, shortening the total build time.
7. The method according to claim 1, wherein in the build output stage, append through the additionalData option of css-loader to the head of each CSS module / * Version:<version number> GitHash:<current commit hash> BuildTime:<ISO time> * / comment, which can be read and reported through document.styleSheets[n].ownerNode.textContent during the real-time runtime of the browser, realizing second-level traceability of the online style version.
8. The method according to any one of claims 1 to 7, wherein the predetermined path rule is: the root directory of the project / src / styles / component name / {version number} / index.scss; The custom loader is registered to the webpack module resolution process through the chainWebpack configuration item in vue.config.js and is limited to act only on *.vue files.
9. A webpack build system, characterized in that, It includes: a version number injection module for executing step a) described in claim 1; a custom loader module for executing steps b)-e) described in claim 1; a parallel sass-loader scheduling module for executing the parallel compilation described in claim 6; and a webpack core compilation module for completing the packaging and output of components and corresponding version SCSS files.
10. A computer-readable storage medium, on which a computer program is stored, wherein when the program is executed by a processor, the steps of the method described in any one of claims 1-9 are implemented; It further includes: an electronic device, the electronic device includes a memory, a processor, and a computer program stored on the memory and executable on the processor, and when the processor executes the program, the method described in any one of claims 1-9 is implemented.