Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor theme tools for dynamic switch theme #2352

Merged
merged 5 commits into from
Oct 22, 2024

Conversation

shenjunjian
Copy link
Collaborator

@shenjunjian shenjunjian commented Oct 22, 2024

PR

PR Checklist

Please check if your PR fulfills the following requirements:

  • The commit message follows our Commit Message Guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • Other... Please describe:

What is the current behavior?

Issue Number: N/A

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • Bug Fixes
    • Removed outdated build scripts that were no longer necessary, streamlining the build process.
  • New Features
    • Introduced a new LESS file for theming, enhancing customization options.
  • Documentation
    • Updated package.json to reflect the latest version and package manager specifications.
  • Chores
    • Cleaned up unused variables and files, improving code maintainability.
    • Eliminated various theme configuration files, impacting styling consistency across the application.

Copy link

coderabbitai bot commented Oct 22, 2024

Walkthrough

This pull request involves the deletion of multiple Gulp build scripts and related files within the project. The removed files included scripts for building low-code bundles, renderless components, themes, and Vue components, along with associated configuration files and LESS variable definitions. The changes also included updates to the package.json file, which reflected modifications in scripts and dependency management. Overall, the deletions streamline the build process by removing outdated or redundant functionalities.

Changes

File Path Change Summary
gulp/buildLowcodeBundle.mjs Deleted file containing a Gulp build script for generating low-code bundle from component API documentation.
gulp/buildRenderless.mjs Deleted file with Gulp tasks for building, releasing, and publishing the @opentiny/renderless package.
gulp/buildTheme.mjs Deleted file managing the theme build process, including LESS compilation and asset copying.
gulp/buildVue.mjs Deleted file intended for building the @opentiny/vue package with minimal functionality.
gulp/themeConcat.mjs Deleted file for concatenating JavaScript theme files from the theme/src directory.
gulp/themeJson.alias.mjs Deleted alias configuration file for UI components.
gulp/themeJson.mjs Deleted file for generating theme.json and Excel file from LESS variable files.
gulpfile.mjs Deleted main Gulp file that imported and exported various build processes.
package.json Updated version to 3.14.0, modified scripts, and dependency management.
packages/theme/build/build-svg-to-css.js Deleted file for converting SVG icons into CSS classes and generating an HTML test page.
packages/theme/build/edit-dir-theme.js Deleted file for managing and building themes.
packages/theme/build/gulp-dist.js Modified file restructuring the build process for theme directories, simplifying tasks.
packages/theme/build/postbuild.js Deleted file for modifying package.json post-build.
packages/theme/build/release.js Modified file for copying and modifying package.json during the release process.
packages/theme/build/replace-img.js Deleted file for modifying image resource paths in index.css.
packages/theme/package.json Updated to include "type": "module" and simplified build scripts.
packages/theme/scripts/build-component-cssvar.js Deleted file for processing theme-related JavaScript files.
packages/theme/src/base/basic-var.less Deleted file containing CSS custom properties for theming.
packages/theme/src/base/index.less Removed import statement for basic-var.less.
packages/theme/src/base/old-basic-vars.less Deleted file containing a comprehensive set of CSS custom properties for theming.
packages/theme/src/base/reset.less Deleted file with CSS reset styles and animations.
packages/theme/src/button/old-theme.less Added new LESS file defining button styles with a specific prefix.
packages/theme/src/card-template/index.less Updated method for injecting CSS variables in card template.
packages/theme/src/index.less Removed block comment with copyright information.
packages/theme/src/old-theme.less Introduced imports for modular styling from other theme files.
packages/theme/src/theme-tool.js Deleted implementation details of TinyThemeTool class, leaving only the declaration.
packages/theme/src/theme.config.js Deleted file containing a mapping of component names to class names for theming.

Possibly related PRs

Suggested labels

refactoring

Suggested reviewers

  • zzcr

A rabbit's poem to celebrate the changes:

In the meadow where code once bloomed,
Scripts now rest, their tasks consumed.
Gulp's old whispers fade away,
New paths emerge, bright as the day.
With every hop, we build anew,
A theme reborn, fresh as the dew! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between de56c23 and cfdcf1c.

📒 Files selected for processing (21)
  • packages/theme/src/base/reset.less (1 hunks)
  • packages/theme/src/svg/index.less (0 hunks)
  • packages/theme/src/theme/aurora-theme/index.js (0 hunks)
  • packages/theme/src/theme/deep-theme/devui.json (0 hunks)
  • packages/theme/src/theme/deep-theme/index.js (0 hunks)
  • packages/theme/src/theme/deep-theme/index.json (0 hunks)
  • packages/theme/src/theme/devui-theme-map.js (0 hunks)
  • packages/theme/src/theme/galaxy-theme/devui.json (0 hunks)
  • packages/theme/src/theme/galaxy-theme/index.js (0 hunks)
  • packages/theme/src/theme/galaxy-theme/index.json (0 hunks)
  • packages/theme/src/theme/generate-theme.js (0 hunks)
  • packages/theme/src/theme/impression-theme/devui.json (0 hunks)
  • packages/theme/src/theme/impression-theme/index.js (0 hunks)
  • packages/theme/src/theme/impression-theme/index.json (0 hunks)
  • packages/theme/src/theme/index.d.ts (0 hunks)
  • packages/theme/src/theme/index.js (0 hunks)
  • packages/theme/src/theme/infinity-theme/component-vars.js (0 hunks)
  • packages/theme/src/theme/infinity-theme/devui.json (0 hunks)
  • packages/theme/src/theme/infinity-theme/index.js (0 hunks)
  • packages/theme/src/theme/infinity-theme/index.json (0 hunks)
  • packages/theme/src/theme/smb-theme/index.js (0 hunks)
💤 Files with no reviewable changes (20)
  • packages/theme/src/svg/index.less
  • packages/theme/src/theme/aurora-theme/index.js
  • packages/theme/src/theme/deep-theme/devui.json
  • packages/theme/src/theme/deep-theme/index.js
  • packages/theme/src/theme/deep-theme/index.json
  • packages/theme/src/theme/devui-theme-map.js
  • packages/theme/src/theme/galaxy-theme/devui.json
  • packages/theme/src/theme/galaxy-theme/index.js
  • packages/theme/src/theme/galaxy-theme/index.json
  • packages/theme/src/theme/generate-theme.js
  • packages/theme/src/theme/impression-theme/devui.json
  • packages/theme/src/theme/impression-theme/index.js
  • packages/theme/src/theme/impression-theme/index.json
  • packages/theme/src/theme/index.d.ts
  • packages/theme/src/theme/index.js
  • packages/theme/src/theme/infinity-theme/component-vars.js
  • packages/theme/src/theme/infinity-theme/devui.json
  • packages/theme/src/theme/infinity-theme/index.js
  • packages/theme/src/theme/infinity-theme/index.json
  • packages/theme/src/theme/smb-theme/index.js
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/theme/src/base/reset.less

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

[e2e-test-warn]
The component to be tested is missing.

The title of the Pull request should look like "fix(vue-renderless): [action-menu, alert] fix xxx bug".

Please make sure you've read our contributing guide

@shenjunjian shenjunjian changed the title Refactor theme tools Refactor theme tools for dynamic switch theme Oct 22, 2024
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Outside diff range and nitpick comments (7)
packages/theme/src/button/old-theme.less (3)

2-2: LGTM: Button prefix class variable.

The '@button-prefix-cls' variable is well-named and uses string interpolation for the CSS prefix. This approach promotes consistency and maintainability.

Consider adding a comment explaining the purpose of this variable for better code documentation.


4-7: LGTM: Button class and custom property definition.

The CSS class is correctly defined using the prefix variable, and the custom property for font weight is well-structured.

Consider the following improvements:

  1. Translate the Chinese comment to English for better international collaboration.
  2. Consider using kebab-case for the custom property name to match CSS conventions, e.g., '--tv-button-font-weight'.

Here's a suggested revision:

.@{button-prefix-cls} {
  // Default button font weight
  --tv-button-font-weight: var(--tv-font-weight-thin);
}

1-7: Overall: Well-structured theme file with minor improvement opportunities.

This new 'old-theme.less' file for buttons is concise and follows good practices for LESS and CSS. It properly imports a custom stylesheet, defines a prefix variable for consistent class naming, and uses CSS custom properties for theming.

To further improve the file:

  1. Consider adding a brief file-level comment explaining the purpose of this 'old-theme' file and its relationship to other theme files.
  2. Ensure that the 'custom.less' import contains all necessary variables (like @css-prefix and --tv-font-weight-thin) used in this file.
  3. If this file is part of a larger theming system, consider documenting how it fits into the overall theme architecture of the project.
packages/theme/package.json (1)

Line range hint 3-35: Summary of changes and potential impact

The changes in this file contribute to the overall refactoring of the theme tools:

  1. Addition of "type": "module" modernizes the package.
  2. Simplification of the build script removes potentially unnecessary steps.
  3. Minor reorganization of scripts improves file structure.

These changes align with the PR objectives of refactoring without introducing functional changes. However, consider the following:

  1. Ensure that the removal of the postbuild step doesn't omit any critical operations.
  2. Verify that these changes integrate well with the broader refactoring efforts across the project.
  3. Update any documentation that might reference the old build process.

To ensure a smooth transition, consider creating or updating a README file in the packages/theme directory that explains the new build process and any changes in how developers should work with this package.

packages/theme/build/gulp-dist.js (3)

Line range hint 50-54: Fix typo in Autoprefixer options.

There's a typo in the Autoprefixer configuration: 'borwsers' should be 'browsers'.

Apply this diff to correct the typo:

-      prefixer({
-        borwsers: ['last 1 version', '> 1%', 'not ie <= 8'],
+      prefixer({
+        browsers: ['last 1 version', '> 1%', 'not ie <= 8'],

73-73: Improve the regular expression in replaceImagesUrl.

The current regex /url\(\.\.\/images\//g may not cover all possible URL formats, such as URLs with single or double quotes or different whitespace. To make the replacement more robust, consider enhancing the regex.

Refactored regex:

-  file = file.replace(/url\(\.\.\/images\//g, 'url(images/')
+  file = file.replace(/url\((['"]?)\.\.\/images\//g, 'url($1images/')

This regex accounts for optional quotes around the URL.


78-78: Consistent task definition in the build task.

In the build task, some tasks are referenced by name (as strings), and others are referenced directly as functions. For consistency and clarity, consider defining all tasks as functions or all as named tasks.

Refactored build task using function references:

-gulp.task('build', gulp.series(concatIndex, concatOldTheme, 'compile', 'copyAssets', replaceImagesUrl))
+gulp.task('build', gulp.series(concatIndex, concatOldTheme, compile, copyAssets, replaceImagesUrl))

Ensure that compile and copyAssets are exported or defined as functions.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c682b1c and de56c23.

📒 Files selected for processing (29)
  • gulp/buildLowcodeBundle.mjs (0 hunks)
  • gulp/buildRenderless.mjs (0 hunks)
  • gulp/buildTheme.mjs (0 hunks)
  • gulp/buildVue.mjs (0 hunks)
  • gulp/themeConcat.mjs (0 hunks)
  • gulp/themeJson.alias.mjs (0 hunks)
  • gulp/themeJson.mjs (0 hunks)
  • gulpfile.mjs (0 hunks)
  • package.json (0 hunks)
  • packages/theme/build/build-svg-to-css.js (0 hunks)
  • packages/theme/build/edit‐dir‐theme.js (0 hunks)
  • packages/theme/build/gulp-dist.js (2 hunks)
  • packages/theme/build/postbuild.js (0 hunks)
  • packages/theme/build/release.js (1 hunks)
  • packages/theme/build/replace-img.js (0 hunks)
  • packages/theme/package.json (2 hunks)
  • packages/theme/scripts/build-component-cssvar.js (0 hunks)
  • packages/theme/src/base/basic-var.less (0 hunks)
  • packages/theme/src/base/index.less (0 hunks)
  • packages/theme/src/base/old-basic-vars.less (0 hunks)
  • packages/theme/src/base/old-theme.js (0 hunks)
  • packages/theme/src/base/old-theme.less (1 hunks)
  • packages/theme/src/base/reset.less (0 hunks)
  • packages/theme/src/button/old-theme.less (1 hunks)
  • packages/theme/src/card-template/index.less (1 hunks)
  • packages/theme/src/index.less (1 hunks)
  • packages/theme/src/old-theme.less (1 hunks)
  • packages/theme/src/theme-tool.js (1 hunks)
  • packages/theme/src/theme.config.js (0 hunks)
💤 Files with no reviewable changes (20)
  • gulp/buildLowcodeBundle.mjs
  • gulp/buildRenderless.mjs
  • gulp/buildTheme.mjs
  • gulp/buildVue.mjs
  • gulp/themeConcat.mjs
  • gulp/themeJson.alias.mjs
  • gulp/themeJson.mjs
  • gulpfile.mjs
  • package.json
  • packages/theme/build/build-svg-to-css.js
  • packages/theme/build/edit‐dir‐theme.js
  • packages/theme/build/postbuild.js
  • packages/theme/build/replace-img.js
  • packages/theme/scripts/build-component-cssvar.js
  • packages/theme/src/base/basic-var.less
  • packages/theme/src/base/index.less
  • packages/theme/src/base/old-basic-vars.less
  • packages/theme/src/base/old-theme.js
  • packages/theme/src/base/reset.less
  • packages/theme/src/theme.config.js
✅ Files skipped from review due to trivial changes (3)
  • packages/theme/src/index.less
  • packages/theme/src/old-theme.less
  • packages/theme/src/theme-tool.js
🧰 Additional context used
🪛 Biome
packages/theme/build/release.js

[error] 10-11: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 11-12: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

🔇 Additional comments (10)
packages/theme/src/button/old-theme.less (1)

1-1: LGTM: Custom stylesheet import.

The import of '../custom.less' is correctly formatted and follows good practices for theme customization.

packages/theme/build/release.js (2)

7-9: LGTM: Proper use of asynchronous file operations.

The code correctly uses fs.promises for asynchronous file reading, which is a good practice to avoid blocking the event loop.


10-12: 🛠️ Refactor suggestion

Consider alternative to delete operator and verify property removal necessity.

While removing 'exports' and 'private' properties might be necessary for the release process, using the delete operator can impact performance. Consider using undefined assignment instead.

Here's a suggested improvement:

-delete packageJson.exports
-delete packageJson.private
+packageJson.exports = undefined
+packageJson.private = undefined

Also, please verify if removing these properties is necessary for the release process. If you can provide more context on why these properties are being removed, it would be helpful.

To verify the impact of these changes, you can run the following script:

This script will help us understand how these properties are used across the project and assess the potential impact of removing them.

🧰 Tools
🪛 Biome

[error] 10-11: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 11-12: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

packages/theme/package.json (3)

35-35: LGTM: Repositioning of "release" script

The "release" script has been repositioned within the "scripts" section. This is a minor change that doesn't affect functionality and is likely due to the removal of other scripts or general file reorganization.


34-34: Verify impact of removing postbuild step

The simplification of the build script by removing the node build/postbuild.js step aligns with the overall goal of streamlining the build process. This change is generally positive as it reduces complexity.

However, we should verify that no critical operations from the removed postbuild step are lost. Let's check the contents of the removed file:

If the file doesn't exist or is empty, we can assume that its functionality has been moved elsewhere or is no longer needed. If it contains significant operations, we may need to ensure those are handled appropriately in the new build process.

✅ Verification successful

Confirmed removal of postbuild step

The build/postbuild.js file does not exist, confirming that removing the postbuild step does not omit any critical operations. The build script simplification is safe and approved.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the contents of the removed postbuild.js file
# Expected result: If the file exists, we'll see its contents and can assess any important operations that might need to be preserved

cat build/postbuild.js

Length of output: 75


3-3: LGTM: Addition of "type": "module"

The addition of "type": "module" is a good practice, indicating that this package should be treated as an ECMAScript module. This aligns with modern JavaScript standards and enables the use of ES modules.

However, there's a discrepancy in the AI summary that needs clarification. It mentions both addition and removal of this field. Let's verify if there was any previous declaration:

packages/theme/src/card-template/index.less (2)

Line range hint 1-156: LGTM: Well-structured use of CSS variables for theming.

The overall structure of the file is well-organized, with consistent use of CSS variables for styling different parts of the card template. This approach facilitates easy theming and customization.

The use of namespaced classes (e.g., @{card-template-prefix-cls}) and CSS variables for various properties (colors, sizes, etc.) is a good practice for maintaining a flexible and maintainable styling system.


20-20: Verify the impact of the new CSS variable injection method.

The change from .component-css-vars-card-template() to .inject-CardTemplate-vars() indicates a shift in how CSS variables are managed for the card template component. This aligns with the broader refactoring of theme tools mentioned in the PR objectives.

To ensure this change doesn't introduce any styling regressions:

  1. Confirm that all necessary variables are properly defined in the new injection method.
  2. Check for any potential impacts on other components that might have depended on the old variable injection method.

Would you like assistance in reviewing the implementation of .inject-CardTemplate-vars() to ensure it covers all necessary variables?

✅ Verification successful

CSS variable injection method verified successfully.

All instances of .component-css-vars-card-template() have been removed, and .inject-CardTemplate-vars() is properly defined and utilized within the card-template component.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining usage of the old mixin
echo "Searching for any remaining usage of .component-css-vars-card-template():"
rg ".component-css-vars-card-template\(\)"

# Search for the definition of the new mixin
echo "Searching for the definition of .inject-CardTemplate-vars():"
rg "\.inject-CardTemplate-vars\s*\(\)\s*\{"

# List all files that include the new mixin to verify its usage
echo "Files using .inject-CardTemplate-vars():"
rg -l "\.inject-CardTemplate-vars\(\)"

Length of output: 670

packages/theme/build/gulp-dist.js (1)

42-44: Verify inclusion of LESS files to prevent redundancy.

Including both ${source}/**/index.less and ${source}/index.less might lead to duplicate imports if index.less aggregates the same files. Verify whether both are necessary or if one can be omitted to prevent redundant processing.

Run the following script to check for duplicates:

✅ Verification successful

Inclusion of LESS files verified; no duplicate @import statements found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find duplicate @import statements in compiled LESS files.

# Test: Search for duplicate imports in index.less.
# Expect: No duplicate @import statements.

grep "@import" ../src/index.less | sort | uniq -d

Length of output: 100


Script:

#!/bin/bash
# Description: Locate all index.less files and check for duplicate @import statements.

# Find all index.less files in the repository
fd --type f --name "index.less" > found_index_less.txt

# Check if any index.less files were found
if [ ! -s found_index_less.txt ]; then
  echo "No index.less files found in the repository."
  exit 0
fi

# Iterate over each found index.less file and check for duplicate @import statements
while IFS= read -r file; do
  echo "Checking duplicate @import statements in: $file"
  grep "@import" "$file" | sort | uniq -d
done < found_index_less.txt

Length of output: 428


Script:

#!/bin/bash
# Description: Locate all index.less files using find and check for duplicate @import statements.

# Find all index.less files in the repository
find . -type f -name "index.less" > found_index_less.txt

# Check if any index.less files were found
if [ ! -s found_index_less.txt ]; then
  echo "No index.less files found in the repository."
  exit 0
fi

# Iterate over each found index.less file and check for duplicate @import statements
while IFS= read -r file; do
  echo "Checking duplicate @import statements in: $file"
  grep "@import" "$file" | sort | uniq -d
done < found_index_less.txt

Length of output: 109470

packages/theme/src/base/old-theme.less (1)

1-447: Well-organized and comprehensive theming variables

The CSS custom properties are clearly defined, consistently named, and cover an extensive range of theming aspects. This enhances maintainability and reusability across the application.

Comment on lines +4 to +6
// 复制package.json/README.md到dist目录
fs.copyFileSync('README.md', path.join('dist', 'README.md'))

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

⚠️ Potential issue

Update comment and consider using asynchronous file operations.

The comment suggests copying both package.json and README.md, but only README.md is being copied. Additionally, consider using asynchronous file operations to avoid blocking the event loop.

Here's a suggested improvement:

-// 复制package.json/README.md到dist目录
-fs.copyFileSync('README.md', path.join('dist', 'README.md'))
+// 复制README.md到dist目录
+await fs.promises.copyFile('README.md', path.join('dist', 'README.md'))
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// 复制package.json/README.md到dist目录
fs.copyFileSync('README.md', path.join('dist', 'README.md'))
// 复制README.md到dist目录
await fs.promises.copyFile('README.md', path.join('dist', 'README.md'))

Comment on lines +20 to +27
function _concatFiles(srcNames, targetName) {
const fileList = fg.sync(srcNames)
const importStr = fileList
.map((filePath) => filePath.replace('../src/', './'))
.map((path) => `@import '${path}';`)
.join('\n')
fs.writeFileSync(targetName, importStr)
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Handle errors when writing files in _concatFiles.

The _concatFiles function uses fs.writeFileSync without error handling. If an error occurs during file writing, it could cause the build process to fail silently. Consider adding try-catch blocks or checking for errors to ensure robust error handling.

Comment on lines +60 to 66
// 4、把 src/svgs 复制到 dist/svgs
gulp.task('copysvgs', () => {
return gulp.src([`${source}/svgs/**`]).pipe(gulp.dest(`${dist}/svgs`))
})

// 5、把 src/images 复制到 dist/images
gulp.task('copyimage', () => {
return gulp.src([`${source}/images/**`]).pipe(gulp.dest(`${dist}/images`))
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Combine copysvgs and copyimage tasks into a single task.

Both tasks copy files from the svgs and images directories to the dist folder. Combining them can simplify the build script and improve maintainability.

Implement the combined task:

gulp.task('copyAssets', () => {
  return gulp
    .src([`${source}/svgs/**`, `${source}/images/**`], { base: source })
    .pipe(gulp.dest(dist));
});

Update the build task accordingly:

-gulp.task('build', gulp.series(concatIndex, concatOldTheme, 'compile', 'copysvgs', 'copyimage', replaceImagesUrl))
+gulp.task('build', gulp.series(concatIndex, concatOldTheme, 'compile', 'copyAssets', replaceImagesUrl))

Comment on lines +71 to +75
const entryFile = path.join('../dist', 'index.css')
let file = fs.readFileSync(entryFile, 'utf8')
file = file.replace(/url\(\.\.\/images\//g, 'url(images/')
fs.writeFileSync(entryFile, file, 'utf8')
cb()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Use asynchronous file operations in replaceImagesUrl.

Similar to earlier, using synchronous methods can block the event loop. Consider refactoring to use asynchronous methods.

Apply this refactor:

function replaceImagesUrl(cb) {
  const entryFile = path.join('../dist', 'index.css');
  fs.readFile(entryFile, 'utf8', (err, data) => {
    if (err) throw err;
    const result = data.replace(/url\((['"]?)\.\.\/images\//g, 'url($1images/');
    fs.writeFile(entryFile, result, 'utf8', (err) => {
      if (err) throw err;
      cb();
    });
  });
}

Comment on lines +25 to +26
.join('\n')
fs.writeFileSync(targetName, importStr)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Avoid using synchronous file operations in an asynchronous context.

Using fs.writeFileSync can block the event loop, which is not ideal in build scripts. It's better to use asynchronous methods like fs.writeFile with callbacks or promises to prevent blocking and improve performance.

Apply this refactor:

-  fs.writeFileSync(targetName, importStr)
+  fs.writeFile(targetName, importStr, (err) => {
+    if (err) throw err;
+  })
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
.join('\n')
fs.writeFileSync(targetName, importStr)
.join('\n')
fs.writeFile(targetName, importStr, (err) => {
if (err) throw err;
})

@zzcr zzcr merged commit 5e8794b into opentiny:dev Oct 22, 2024
4 checks passed
@shenjunjian shenjunjian deleted the refactor-theme-tools branch November 7, 2024 02:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants