Skip to content

Conversation

@xiaoyatong
Copy link
Collaborator

@xiaoyatong xiaoyatong commented Aug 1, 2025

🤔 这个变动的性质是?

  • 新特性提交
  • 日常 bug 修复
  • 站点、文档改进
  • 演示代码改进
  • 组件样式/交互改进
  • TypeScript 定义更新
  • 包体积优化
  • 性能优化
  • 功能增强
  • 国际化改进
  • 重构
  • 代码风格优化
  • 测试用例
  • 分支合并
  • 其他改动(是关于什么的改动?)

🔗 相关 Issue

💡 需求背景和解决方案

☑️ 请求合并前的自查清单

⚠️ 请自检并全部勾选全部选项⚠️

  • 文档已补充或无须补充
  • 代码演示已提供或无须提供
  • TypeScript 定义已补充或无须补充
  • fork仓库代码是否为最新避免文件冲突
  • Files changed 没有 package.json lock 等无关文件

Summary by CodeRabbit

  • 新功能

    • 发布了全新的 @nutui/inject-ui-styles 包,用于自动注入 NutUI 组件样式,支持 HarmonyOS 和 React Native 等平台。
    • 提供 Babel 插件,可在构建过程中自动导入组件样式文件。
    • 新增详细的使用文档和配置示例,便于集成和上手。
  • 文档

    • 添加了 README,说明包的用途、配置方法及使用示例。
  • 杂项

    • 新增包的配置文件(如 .gitignorepackage.jsontsconfig.json、Rollup 构建配置等)。

@coderabbitai
Copy link

coderabbitai bot commented Aug 1, 2025

Walkthrough

本次变更在 packages/nutui-inject-ui-styles 目录下新增了一个用于自动注入 NutUI 组件样式的 Babel 插件包。新增内容包括插件核心源码、类型定义、构建配置、包描述文件、README 文档、TypeScript 配置及相关忽略文件。该插件主要用于在构建过程中根据组件导入自动插入相应的样式文件。

Changes

Cohort / File(s) Change Summary
包管理与配置文件
package.json, tsconfig.json, .gitignore
新增包的元数据、TypeScript 配置和 Git 忽略规则。
构建相关
rollup.config.js
新增 Rollup 构建配置,指定入口、输出、插件及外部依赖。
类型定义
src/type.ts, types/index.d.ts
新增 IOptions 接口及 babelComponentStyle 函数类型声明,描述插件参数与导出。
核心插件实现
src/babel-component-style.ts, src/index.ts
实现 Babel 插件主逻辑,自动检测组件导入并插入样式文件,同时暴露主入口。
文档
README.md
新增包的使用说明、配置示例及功能介绍。

Sequence Diagram(s)

sequenceDiagram
    participant UserCode as 用户代码
    participant BabelPlugin as babelComponentStyle 插件
    participant FileSystem as 文件系统

    UserCode->>BabelPlugin: 导入 NutUI 组件
    BabelPlugin->>BabelPlugin: 检查导入声明
    BabelPlugin->>FileSystem: 检查样式文件是否存在
    FileSystem-->>BabelPlugin: 返回文件存在/不存在
    alt 样式文件存在
        BabelPlugin->>UserCode: 插入样式 import 声明
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 分钟

Suggested reviewers

  • oasis-cloud
  • Alex-huxiyang

Poem

兔子在代码林间跳,
新插件把样式巧妙注入好。
配置与类型都齐全,
构建流程顺畅跑。
NutUI 组件换新装,
自动导入乐逍遥!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this 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.

@github-actions github-actions bot added action:review This PR needs more reviews (less than 2 approvals) 3.x Target branch 3.x labels Aug 1, 2025
@codecov
Copy link

codecov bot commented Aug 1, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.14%. Comparing base (09227c8) to head (0fb82e4).
⚠️ Report is 1 commits behind head on feat_v3.x.

Additional details and impacted files
@@            Coverage Diff             @@
##           feat_v3.x    #3318   +/-   ##
==========================================
  Coverage      88.14%   88.14%           
==========================================
  Files            290      290           
  Lines          19110    19110           
  Branches        2960     2960           
==========================================
  Hits           16844    16844           
  Misses          2261     2261           
  Partials           5        5           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@oasis-cloud oasis-cloud merged commit 6ac50fd into jdf2e:feat_v3.x Aug 1, 2025
8 checks passed
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: 8

🧹 Nitpick comments (8)
packages/nutui-inject-ui-styles/.gitignore (1)

1-3: 补充忽略构建产物目录

Rollup 构建该子包时通常会生成 dist/lib/ 等产物目录,当前 .gitignore 未覆盖,容易把编译结果误提交进仓库。建议顺便屏蔽常见日志与缓存文件。

 .idea/
 .vscode/
 node_modules/
+# 打包产物
+dist/
+lib/
+# 日志 & 缓存
+npm-debug.log*
+yarn-error.log*
+.DS_Store
packages/nutui-inject-ui-styles/rollup.config.js (1)

6-20: Rollup配置结构合理

构建配置清晰合理,正确设置了外部依赖排除和TypeScript支持。建议为配置对象添加注释说明其用途,提高代码可读性。

可以考虑为base配置对象添加注释:

 const base = {
+  // 排除 Taro 服务依赖,避免打包到最终产物中
   external: ['@tarojs/service'],
+  // 使用 TypeScript 插件处理 .ts 文件
   plugins: [ts()],
 }
packages/nutui-inject-ui-styles/README.md (1)

21-37: 废弃的Vite插件配置说明可以优化

既然Vite插件方法已经废弃,建议:

  1. 将废弃部分移到文档末尾或单独的"废弃功能"章节
  2. 明确说明废弃的原因和替代方案
  3. 考虑在未来版本中完全移除废弃内容
packages/nutui-inject-ui-styles/tsconfig.json (1)

1-27: TypeScript配置完整且合理

TypeScript配置设置全面,正确继承了根配置并针对包的需求进行了定制。编译选项设置合理,支持源码映射和类型声明文件生成,与Rollup构建配置保持一致。

可以考虑添加 "strict": true 来启用所有严格类型检查选项,替代单独设置多个严格选项:

 "compilerOptions": {
+  "strict": true,
   "allowSyntheticDefaultImports": true,
   "experimentalDecorators": true,
   "moduleResolution": "node",
-  "noImplicitAny": false,
-  "noUnusedLocals": true,
-  "noUnusedParameters": true,
   "removeComments": false,
   "resolveJsonModule": true,
   "skipLibCheck": true,
-  "strictNullChecks": true,
packages/nutui-inject-ui-styles/types/index.d.ts (1)

16-16: 考虑使用命名导出替代默认导出

ESLint 提示不应使用 'default' 作为导出名称。虽然这在 TypeScript 中是有效的,但如果项目的 ESLint 规则要求避免这种模式,可以考虑使用命名导出。

-export { babelComponentStyle as default }
+export { babelComponentStyle }
+export default babelComponentStyle
packages/nutui-inject-ui-styles/src/babel-component-style.ts (3)

5-109: 考虑将组件列表外部化以便于维护

当前组件列表是硬编码的,包含 103 个组件。随着 NutUI 的发展,这个列表需要手动更新。建议:

  1. 将列表移至独立的配置文件
  2. 或从 NutUI 包中动态获取
  3. 或在 IOptions 中提供自定义组件列表的选项

建议创建一个独立的配置文件:

// components.config.ts
export const DEFAULT_COMPONENTS = [
  'button',
  'cell',
  // ... 其他组件
] as const

export type ComponentName = typeof DEFAULT_COMPONENTS[number]

然后在主文件中导入:

+import { DEFAULT_COMPONENTS } from './components.config'
+
-const list = [
-  'button',
-  // ... 所有组件
-]
+const list = DEFAULT_COMPONENTS

127-128: 改进错误日志记录

使用 console.log 记录警告信息不够规范。建议使用更合适的日志级别或允许用户配置日志行为。

-console.log(`warn: cannot reslove ${realNamePackage}`)
+console.warn(`[nutui-inject-ui-styles] Cannot resolve package: ${realNamePackage}`)

或者添加日志配置选项:

interface IOptions {
  // ... 现有字段
  onWarn?: (message: string) => void
}

// 使用时
const warn = options.onWarn || console.warn
warn(`[nutui-inject-ui-styles] Cannot resolve package: ${realNamePackage}`)

139-150: 考虑缓存文件存在性检查结果

每次导入都会进行同步文件系统访问(accessSync),这可能影响构建性能。建议添加缓存机制。

// 在模块级别添加缓存
const styleFileCache = new Map<string, boolean>()

// 在检查文件时使用缓存
function checkStyleFile(path: string): boolean {
  if (styleFileCache.has(path)) {
    return styleFileCache.get(path)!
  }
  
  try {
    accessSync(path)
    styleFileCache.set(path, true)
    return true
  } catch {
    styleFileCache.set(path, false)
    return false
  }
}

// 使用缓存的版本
if (checkStyleFile(importpath)) {
  const importCss = t.importDeclaration([], t.stringLiteral(importpath))
  const programPath = path.findParent((path) => path.isProgram())
  programPath.unshiftContainer('body', importCss)
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 09227c8 and 0fb82e4.

⛔ Files ignored due to path filters (2)
  • packages/nutui-inject-ui-styles/dist/index.js is excluded by !**/dist/**
  • packages/nutui-inject-ui-styles/dist/index.js.map is excluded by !**/dist/**, !**/*.map
📒 Files selected for processing (9)
  • packages/nutui-inject-ui-styles/.gitignore (1 hunks)
  • packages/nutui-inject-ui-styles/README.md (1 hunks)
  • packages/nutui-inject-ui-styles/package.json (1 hunks)
  • packages/nutui-inject-ui-styles/rollup.config.js (1 hunks)
  • packages/nutui-inject-ui-styles/src/babel-component-style.ts (1 hunks)
  • packages/nutui-inject-ui-styles/src/index.ts (1 hunks)
  • packages/nutui-inject-ui-styles/src/type.ts (1 hunks)
  • packages/nutui-inject-ui-styles/tsconfig.json (1 hunks)
  • packages/nutui-inject-ui-styles/types/index.d.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: oasis-cloud
PR: jdf2e/nutui-react#2700
File: src/packages/animatingnumbers/animatingnumbers.harmony.css:25-32
Timestamp: 2024-11-06T05:56:06.800Z
Learning: 在优化 NutUI React 动画性能时,添加 `will-change` 属性可能会对布局产生影响,需要谨慎使用。
📚 Learning: 在优化 nutui react 动画性能时,添加 `will-change` 属性可能会对布局产生影响,需要谨慎使用。...
Learnt from: oasis-cloud
PR: jdf2e/nutui-react#2700
File: src/packages/animatingnumbers/animatingnumbers.harmony.css:25-32
Timestamp: 2024-11-06T05:56:06.800Z
Learning: 在优化 NutUI React 动画性能时,添加 `will-change` 属性可能会对布局产生影响,需要谨慎使用。

Applied to files:

  • packages/nutui-inject-ui-styles/README.md
  • packages/nutui-inject-ui-styles/src/babel-component-style.ts
📚 Learning: 在`trendarrow`组件(`src/packages/trendarrow/trendarrow.taro.tsx`)中,css变量在鸿蒙系统(harmony os)中可能未被完全支持,导致兼容...
Learnt from: oasis-cloud
PR: jdf2e/nutui-react#2540
File: src/packages/trendarrow/trendarrow.taro.tsx:29-30
Timestamp: 2024-11-06T02:16:07.069Z
Learning: 在`TrendArrow`组件(`src/packages/trendarrow/trendarrow.taro.tsx`)中,CSS变量在鸿蒙系统(Harmony OS)中可能未被完全支持,导致兼容性问题。因此,使用硬编码的十六进制颜色值可以确保在鸿蒙系统上的正确显示。

Applied to files:

  • packages/nutui-inject-ui-styles/README.md
  • packages/nutui-inject-ui-styles/types/index.d.ts
  • packages/nutui-inject-ui-styles/src/type.ts
  • packages/nutui-inject-ui-styles/src/babel-component-style.ts
📚 Learning: when changes are made to the `filelist` state in the `src/packages/uploader/uploader.taro.tsx` file,...
Learnt from: Alex-huxiyang
PR: jdf2e/nutui-react#2416
File: src/packages/uploader/uploader.taro.tsx:230-230
Timestamp: 2024-07-05T02:58:57.992Z
Learning: When changes are made to the `fileList` state in the `src/packages/uploader/uploader.taro.tsx` file, ensure to generate unit tests to cover these changes.

Applied to files:

  • packages/nutui-inject-ui-styles/tsconfig.json
🧬 Code Graph Analysis (3)
packages/nutui-inject-ui-styles/src/index.ts (2)
packages/nutui-inject-ui-styles/types/index.d.ts (1)
  • babelComponentStyle (16-16)
packages/nutui-inject-ui-styles/src/babel-component-style.ts (1)
  • babelComponentStyle (168-172)
packages/nutui-inject-ui-styles/types/index.d.ts (2)
packages/nutui-inject-ui-styles/src/type.ts (1)
  • IOptions (1-6)
packages/nutui-inject-ui-styles/src/babel-component-style.ts (1)
  • babelComponentStyle (168-172)
packages/nutui-inject-ui-styles/src/babel-component-style.ts (3)
packages/nutui-inject-ui-styles/dist/index.js (1)
  • list (26-129)
packages/nutui-inject-ui-styles/src/type.ts (1)
  • IOptions (1-6)
src/utils/taro/platform.ts (1)
  • harmony (3-7)
🪛 ESLint
packages/nutui-inject-ui-styles/types/index.d.ts

[error] 16-16: 'default' is restricted from being used as an exported name.

(no-restricted-exports)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: build
  • GitHub Check: lint
  • GitHub Check: test
🔇 Additional comments (3)
packages/nutui-inject-ui-styles/src/type.ts (1)

1-6: 接口设计合理,HarmonyOS兼容性考虑周到

这个接口设计清晰简洁,特别是针对鸿蒙系统CSS变量不支持的问题提供了专门的处理方案。注释说明了style属性的作用,这与之前学习到的鸿蒙系统CSS变量兼容性问题一致。

packages/nutui-inject-ui-styles/src/index.ts (1)

1-3: 入口文件实现简洁清晰

作为包的主入口文件,实现简洁明了,遵循了标准的模块导出模式。

packages/nutui-inject-ui-styles/package.json (1)

30-35: 确认并完善 Taro v4 兼容性依赖

由于已将 @tarojs/service 升级至 v4(含 Webpack5、插件化架构、生命周期及样式处理等破坏性变更),请务必确认并调整以下内容:

  • 本包是否仅面向 Taro v4 设计?若是,请在 README 或 peerDependencies 中明确标注最低版本。
  • 是否引入并声明了对应框架插件(如 @tarojs/plugin-framework-react@tarojs/plugin-framework-vue2@tarojs/plugin-framework-vue3)?
  • 对于 Vue2/React 项目,是否在 devDependencies 中添加了必要的编译依赖:
    • Vue2:@vue/babel-preset-jsx
    • React:@pmmmwh/react-refresh-webpack-pluginreact-refresh
  • 如需保留对 Taro v3 的兼容性,请评估并区分版本策略(降级依赖或双版本支持)。

{
"name": "@nutui/inject-ui-styles",
"version": "0.0.1",
"description": "",
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

请填写缺失的包元数据字段

包的 description、author、homepage 字段为空,repository 和 bugs 的 URL 也未填写。这些信息对于包的文档和维护很重要,建议补充完整。

-    "description": "",
+    "description": "Babel plugin for injecting NutUI component styles automatically",
     "keywords": [
         "Taro",
         "Plugin"
     ],
-    "author": "",
-    "homepage": "",
+    "author": "NutUI Team",
+    "homepage": "https://github.com/jdf2e/nutui-react/tree/main/packages/nutui-inject-ui-styles",
     "license": "MIT",
     "main": "dist/index.js",
     "typings": "types/index.d.ts",
     "files": [
         "dist",
         "index.js",
         "types"
     ],
     "repository": {
         "type": "git",
-        "url": ""
+        "url": "https://github.com/jdf2e/nutui-react.git"
     },
     "scripts": {
         "build": "rollup -c",
         "dev": "rollup -c -w"
     },
     "bugs": {
-        "url": ""
+        "url": "https://github.com/jdf2e/nutui-react/issues"
     },

Also applies to: 9-10, 21-22, 28-29

🤖 Prompt for AI Agents
In packages/nutui-inject-ui-styles/package.json at lines 4, 9-10, 21-22, and
28-29, the package metadata fields such as description, author, homepage,
repository URL, and bugs URL are missing or empty. Fill in these fields with
accurate and complete information relevant to the package to improve
documentation and maintenance. Ensure the description briefly explains the
package purpose, author includes contact or name, homepage points to the project
site, and repository and bugs URLs link to the correct source and issue tracker
locations.

Comment on lines +14 to +18
"files": [
"dist",
"index.js",
"types"
],
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

验证 files 数组中的路径配置

files 数组同时包含了 "dist" 和 "index.js"。如果 index.js 实际上位于 dist 目录下(作为 main 入口),这个配置可能是冗余的。请确认 index.js 文件的实际位置。


🏁 Script executed:

#!/bin/bash
# 检查 index.js 文件的位置
fd -t f "^index\.js$" packages/nutui-inject-ui-styles --max-depth 2

Length of output: 115


删除冗余的 files 配置

packages/nutui-inject-ui-styles/package.json 中的 files 数组包含了 "index.js",但实际上该项目根目录下并不存在 index.js,只有 dist/index.js 会被打包。请将 "index.js"files 中移除,以避免发布时出现遗漏或误导。

需要修改的文件:

  • packages/nutui-inject-ui-styles/package.json

建议改动:

-  "files": [
-    "dist",
-    "index.js",
-    "types"
-  ],
+  "files": [
+    "dist",
+    "types"
+  ],
🤖 Prompt for AI Agents
In packages/nutui-inject-ui-styles/package.json around lines 14 to 18, the
"files" array includes "index.js" which does not exist in the project root and
may cause confusion or packaging errors. Remove the "index.js" entry from the
"files" array so that only existing paths like "dist" and "types" are included
for packaging.

Comment on lines +11 to +19
```js
const injectUIStyles = require('@nutui/inject-ui-styles')

{
[
[injectUIStyles({})]
]
}
```
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

文档中的使用示例与实际导出不匹配

文档中的使用示例存在严重问题:示例中使用的是 injectUIStyles,但根据 src/index.ts 文件,包实际导出的是 babelComponentStyle。这会导致用户按照文档使用时出现运行时错误。

需要修正使用示例:

-const injectUIStyles = require('@nutui/inject-ui-styles')
+const babelComponentStyle = require('@nutui/inject-ui-styles')

 {
   [
-    [injectUIStyles({})]
+    [babelComponentStyle]
   ]
 }
📝 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
```js
const injectUIStyles = require('@nutui/inject-ui-styles')
{
[
[injectUIStyles({})]
]
}
```
const babelComponentStyle = require('@nutui/inject-ui-styles')
{
[
[babelComponentStyle]
]
}
🤖 Prompt for AI Agents
In packages/nutui-inject-ui-styles/README.md around lines 11 to 19, the usage
example incorrectly references injectUIStyles, but the actual export from
src/index.ts is babelComponentStyle. Update the example code to use
babelComponentStyle instead of injectUIStyles to match the real export and
prevent runtime errors for users following the documentation.

Comment on lines +118 to +119
// 检查是否已经插入过或者有其他条件判断
// if (state.file.get('hasInsertedImport')) return
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

启用重复导入预防机制

代码中注释掉了防止重复插入样式的逻辑。如果不启用,可能会导致:

  1. 同一样式文件被多次导入
  2. 构建产物体积增大
  3. 潜在的样式冲突

建议启用并完善这个机制:

 ImportDeclaration(path) {
   if (path.node.source.value === pName && path.node.specifiers.length) {
-    // 检查是否已经插入过或者有其他条件判断
-    // if (state.file.get('hasInsertedImport')) return
+    // 获取已插入的样式集合
+    const insertedStyles = path.hub.file.metadata.insertedStyles || new Set()
+    
     const realNamePackage = nodepath.normalize(cName)
     // ... 其他代码
     
     path.node.specifiers.forEach((specifier) => {
       const name = specifier.imported.name.toLowerCase()
+      
+      // 检查是否已经插入过该组件的样式
+      if (insertedStyles.has(name)) return
+      
       // ... 其他代码
       
       try {
         accessSync(importpath)
         const importCss = t.importDeclaration([], t.stringLiteral(importpath))
         const programPath = path.findParent((path) => path.isProgram())
         programPath.unshiftContainer('body', importCss)
+        
+        // 记录已插入的样式
+        insertedStyles.add(name)
       } catch (e) {
         /* empty */
       }
     })
-    // 设置一个标记,防止重复插入
-    // state.file.set('hasInsertedImport', true)
+    
+    // 保存插入记录
+    path.hub.file.metadata.insertedStyles = insertedStyles
   }
 }

Also applies to: 151-153

🤖 Prompt for AI Agents
In packages/nutui-inject-ui-styles/src/babel-component-style.ts around lines
118-119 and 151-153, the code that prevents duplicate style imports is commented
out, which can cause multiple imports of the same style, increasing build size
and causing style conflicts. Re-enable this duplicate import prevention by
uncommenting and properly implementing the check using
state.file.get('hasInsertedImport') or a similar mechanism to track if the style
has already been inserted, and return early if so.

Comment on lines +160 to +166
function harmony() {
return (process.env.TARO_ENV as any).indexOf('harmony') > -1
}

function dynamic() {
return (process.env.TARO_ENV as any).indexOf('dynamic') > -1
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

改进环境检测函数的类型安全性和健壮性

当前实现存在以下问题:

  1. 使用 as any 失去类型安全
  2. 未处理环境变量未定义的情况
  3. 使用 indexOf 而非更现代的方法
 function harmony() {
-  return (process.env.TARO_ENV as any).indexOf('harmony') > -1
+  const env = process.env.TARO_ENV || ''
+  return env.toLowerCase().includes('harmony')
 }

 function dynamic() {
-  return (process.env.TARO_ENV as any).indexOf('dynamic') > -1
+  const env = process.env.TARO_ENV || ''
+  return env.toLowerCase().includes('dynamic')
 }

另外,考虑到 src/utils/taro/platform.ts 中已有类似的 harmony() 函数,建议复用现有实现以保持一致性。

📝 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
function harmony() {
return (process.env.TARO_ENV as any).indexOf('harmony') > -1
}
function dynamic() {
return (process.env.TARO_ENV as any).indexOf('dynamic') > -1
}
function harmony() {
const env = process.env.TARO_ENV || ''
return env.toLowerCase().includes('harmony')
}
function dynamic() {
const env = process.env.TARO_ENV || ''
return env.toLowerCase().includes('dynamic')
}
🤖 Prompt for AI Agents
In packages/nutui-inject-ui-styles/src/babel-component-style.ts around lines 160
to 166, the environment detection functions use 'as any' which loses type
safety, do not handle undefined environment variables, and use outdated
'indexOf' for string checks. To fix this, remove 'as any', add checks to ensure
process.env.TARO_ENV is defined before calling methods on it, replace 'indexOf'
with the more modern 'includes' method, and refactor to reuse the existing
harmony() function from src/utils/taro/platform.ts to maintain consistency and
improve robustness.

Comment on lines +168 to +172
export function babelComponentStyle(
options: IOptions = { cName: '@nutui/nutui-react-taro', pName: '' }
) {
return injectCSS(options)
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

改进默认参数配置

默认的 pName 为空字符串,这意味着如果用户不提供此参数,插件将无法匹配任何导入。建议要么将其设为必需参数,要么提供有意义的默认值。

 export function babelComponentStyle(
-  options: IOptions = { cName: '@nutui/nutui-react-taro', pName: '' }
+  options: IOptions = { 
+    cName: '@nutui/nutui-react-taro', 
+    pName: '@nutui/nutui-react-taro'  // 使用相同的默认值
+  }
 ) {
   return injectCSS(options)
 }

或者将 pName 设为可选并在代码中处理:

export function babelComponentStyle(options: Partial<IOptions> = {}) {
  const defaultOptions: IOptions = {
    cName: '@nutui/nutui-react-taro',
    pName: options.cName || '@nutui/nutui-react-taro'
  }
  return injectCSS({ ...defaultOptions, ...options })
}
🤖 Prompt for AI Agents
In packages/nutui-inject-ui-styles/src/babel-component-style.ts around lines 168
to 172, the default parameter pName is an empty string, causing the plugin to
fail matching imports if the user does not provide it. To fix this, make pName
optional in the options parameter and assign it a meaningful default value
inside the function by merging user options with defaults, ensuring pName
defaults to a valid string like the default cName if not provided.

Comment on lines +1 to +6
interface IOptions {
pName: string
cName: string
// 默认加载组件的 scss 样式文件,鸿蒙由于不支持 css 变量,优先加载无css 变量的 style.harmony.css 文件。
style?: boolean | 'css'
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

避免接口定义重复

IOptions 接口在这里重复定义了(在 src/type.ts 中也有相同定义)。建议从 type.ts 导入而不是重复定义。

+import { IOptions } from './type'
+
-interface IOptions {
-  pName: string
-  cName: string
-  // 默认加载组件的 scss 样式文件,鸿蒙由于不支持 css 变量,优先加载无css 变量的 style.harmony.css 文件。
-  style?: boolean | 'css'
-}

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In packages/nutui-inject-ui-styles/types/index.d.ts lines 1 to 6, the IOptions
interface is redundantly defined here and also in src/type.ts. Remove this local
definition and instead import the IOptions interface from src/type.ts to avoid
duplication and maintain consistency.

Comment on lines +7 to +15
declare function babelComponentStyle(options?: IOptions): ({
types: t,
}: {
types: any
}) => {
visitor: {
ImportDeclaration(path: any): void
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

使用正确的 Babel 类型定义

参数 types: any 应该使用 Babel 提供的正确类型定义,以提高类型安全性。

+import type { PluginObj, types as BabelTypes } from '@babel/core'
+
-declare function babelComponentStyle(options?: IOptions): ({
-  types: t,
-}: {
-  types: any
-}) => {
-  visitor: {
-    ImportDeclaration(path: any): void
-  }
-}
+declare function babelComponentStyle(options?: IOptions): (api: {
+  types: typeof BabelTypes
+}) => PluginObj

需要在 package.json 中添加 @babel/core 的类型定义:

"devDependencies": {
  "@types/babel__core": "^7.20.0",
  // ... 其他依赖
}
🤖 Prompt for AI Agents
In packages/nutui-inject-ui-styles/types/index.d.ts around lines 7 to 15, the
parameter types is currently typed as any, which reduces type safety. Replace
the any type with the correct Babel type definitions by importing the
appropriate types from @babel/core. Also, ensure that @types/babel__core is
added as a devDependency in package.json to provide these type definitions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

3.x Target branch 3.x action:review This PR needs more reviews (less than 2 approvals) size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants