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

feat: add plugin to remove rtl #2673

Merged
merged 9 commits into from
Nov 1, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions packages/nutui-optimization-css/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
通过配置 postcss 对组件库的 css 进行优化。

1. Taro 环境下的配置示例

```text
{
"mini": {
"postcss": {
"@nutui/opt-css": {
"enable": true,
"config": {
"removeRtl": true,
"cssVariables": {
"include": [path.join(__dirname, 'variables.scss')],
"exclude": ["--nutui-color-primary-text"],
"type": "replace"
}
}
}
}
}
}
```

配置说明:

1. removeRtl:删除 rtl 相关样式
2. cssVariables
- include: 指定css变量的文件
- exclude: 设置哪些 css 变量不进行替换, 在 JS 控制 css 变量时可以使用 exclude 指定
- type: css 变量的替换方案,默认不处理,当设置 replace 时,可将 css 变量替换为实际值
18 changes: 18 additions & 0 deletions packages/nutui-optimization-css/build.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { defineBuildConfig } from 'unbuild'

export default defineBuildConfig({
failOnWarn: false,
entries: [
{
input: 'src/index',
outDir: 'dist',
oasis-cloud marked this conversation as resolved.
Show resolved Hide resolved
format: 'cjs',
ext: 'cjs',
},
],
outDir: 'dist',
externals: ['postcss', 'postcss-css-variables', 'postcss-scss'],
rollup: {
emitCJS: true,
},
})
oasis-cloud marked this conversation as resolved.
Show resolved Hide resolved
26 changes: 26 additions & 0 deletions packages/nutui-optimization-css/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"name": "@nutui/opt-css",
oasis-cloud marked this conversation as resolved.
Show resolved Hide resolved
"version": "1.0.0",
"description": "remove rtl",
"main": "dist/index.cjs",
"scripts": {
"build": "unbuild",
"test": "pnpm build && node test/case.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/lodash": "^4.17.1",
"@types/node": "^20.14.11",
"@types/postcss-css-variables": "^0.18.3",
"ts-node": "^10.9.2",
"unbuild": "^2.0.0"
},
"dependencies": {
"lodash": "^4.17.21",
"postcss": "^8.4.39",
"postcss-css-variables": "^0.19.0",
"postcss-scss": "^4.0.9"
}
}
3 changes: 3 additions & 0 deletions packages/nutui-optimization-css/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { profileGuidedOptimization } from './postcss-plugins'

export default profileGuidedOptimization
95 changes: 95 additions & 0 deletions packages/nutui-optimization-css/src/postcss-plugins/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import postcss from 'postcss'
import { merge } from 'lodash'
import cssVariables from 'postcss-css-variables'
import { parse } from 'postcss-scss'
import * as fs from 'fs'

export type CSSVariable = `--${string}`
export type FilePath = string

export interface Options {
removeRtl: boolean
cssVariables: {
include: FilePath[]
exclude: CSSVariable[]
type: 'normal' | 'replace'
}
}

function removeRtl(rule: any, canRemove: boolean) {
oasis-cloud marked this conversation as resolved.
Show resolved Hide resolved
if (!canRemove) return

const sourceFile = rule.source.input.file
if (
sourceFile &&
sourceFile.indexOf('@nutui') === -1 &&
sourceFile.indexOf('@dongdesign') === -1
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

检查代码中 'dongdesign' 的引用是否正确

在第 25 行和第 26 行中,代码检查了 sourceFile 是否不包含 '@dongdesign'。请确认这里的 '@dongdesign' 是否应替换为 '@nutui',以确保包名的一致性,避免混淆。

建议修改如下:

-     sourceFile.indexOf('@dongdesign') === -1
+     sourceFile.indexOf('@nutui') === -1

Committable suggestion was skipped due to low confidence.

)
return
if (
rule.selector.indexOf('nut-rtl') > -1 ||
rule.selector.indexOf('[dir=rtl]') > -1
)
rule.remove()
}

async function replaceCssVariables(
root,
cssVariablesContent: string[],
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

为函数参数添加类型注解

在异步函数 replaceCssVariables 中,参数 root 未指定类型。建议为其添加类型注解,例如 postcss.Root,以增强类型检查和代码可读性。

修改如下:

- async function replaceCssVariables(
-   root,
+ async function replaceCssVariables(
+   root: postcss.Root,
    cssVariablesContent: string[],
    exclude: string[] = []
  ) {
📝 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
async function replaceCssVariables(
root,
cssVariablesContent: string[],
async function replaceCssVariables(
root: postcss.Root,
cssVariablesContent: string[],

exclude: string[] = []
) {
cssVariablesContent.push(root.toResult().css)
const replacedCss = await postcss([
cssVariables({
preserve: (declaration) => {
if (exclude.includes(declaration.prop)) return true
return false
},
}),
]).process(cssVariablesContent.join('\n'), { parser: parse, from: undefined })
.css

const replacedRoot = postcss.parse(replacedCss)
root.raws = replacedRoot.raws
root.nodes = replacedRoot.nodes
}

export function profileGuidedOptimization(opts: Options) {
const defaultConfig = {
removeRtl: false,
cssVariables: {
include: [],
type: 'normal',
},
}
const config = merge(defaultConfig, opts)
const cssVariablesContent: string[] = []
if (config.cssVariables.type !== 'normal') {
config.cssVariables.include.forEach((p: string) => {
let content = ''
try {
// 从绝对路径读取 CSS 变量的内容
content = fs.readFileSync(p).toString()
} catch (e) {
content = ''
}
cssVariablesContent.push(content)
})
}

return {
postcssPlugin: 'postcss-dongdesign-optimization-css',
oasis-cloud marked this conversation as resolved.
Show resolved Hide resolved
OnceExit(root) {
if (config.cssVariables.type === 'replace') {
replaceCssVariables(
root,
cssVariablesContent,
config.cssVariables.exclude
)
}
},
oasis-cloud marked this conversation as resolved.
Show resolved Hide resolved
Rule(rule) {
removeRtl(rule, opts.removeRtl)
},
oasis-cloud marked this conversation as resolved.
Show resolved Hide resolved
}
}
33 changes: 33 additions & 0 deletions packages/nutui-optimization-css/test/case.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const postcss = require('postcss')
const path = require('path')
const profileGuidedOptimization = require('../dist/index.cjs')
oasis-cloud marked this conversation as resolved.
Show resolved Hide resolved

const css = `
.nut-address-footer-btn {
background: linear-gradient(135deg, var(--nutui-color-primary-stop-1, #f53d6d) 0%, var(--nutui-color-primary-stop-2, #fa2c19) 100%);
color: var(--nutui-color-primary-text, #ffffff)
}
[dir=rtl] .ca, .xcdd {
margin-left: 0;
margin-right: 9px
}
[dir=rtl] .nut-address-exist-item-info, .nut-rtl .nut-address-exist-item-info {
margin-left: 0;
margin-right: 9px
}
`

postcss([
profileGuidedOptimization({
removeRtl: true,
cssVariables: {
include: [path.join(__dirname, 'variables.scss')],
exclude: ['--nutui-color-primary-text'],
type: 'replace',
},
}),
])
.process(css, { from: undefined })
.then((res) => {
console.log(res.css.toString())
})
oasis-cloud marked this conversation as resolved.
Show resolved Hide resolved
4 changes: 4 additions & 0 deletions packages/nutui-optimization-css/test/variables.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
:root {
--nutui-color-primary-stop-1: red;
--nutui-color-primary-text: green;
}
4 changes: 4 additions & 0 deletions packages/nutui-optimization-css/test/variables.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
:root {
--nutui-color-primary-text: blue;
--nutui-color-primary-stop-1: yellow;
}
Loading
Loading