cus-base-ui 0.2.3 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +145 -55
  2. package/package.json +1 -1
  3. package/scripts/ui-cli.ts +166 -2
package/README.md CHANGED
@@ -1,55 +1,145 @@
1
- # CUS-UI CLI (Remote/NPM Ready)
2
-
3
- Bộ công cụ CLI giúp bạn cài đặt các components từ thư viện UI này vào bất kỳ dự án React nào khác thông qua `npx`.
4
-
5
- ## 🚀 Cách sử dụng từ dự án khác
6
-
7
- Bạn không cần cài đặt gì cả, chỉ cần đứng tại thư mục dự án của bạn và gõ:
8
-
9
- ### 1. Khởi tạo dự án (Lần đầu)
10
- ```bash
11
- npx cus-base-ui init
12
- ```
13
- Lệnh này sẽ tự động cài các gói cần thiết (`clsx`, `tailwind-merge`) và tạo file `src/lib/utils/cn.ts`.
14
-
15
- ### 2. Thêm Component
16
- ```bash
17
- npx cus-base-ui add button input switch
18
- ```
19
- *Lưu ý: CLI sẽ tự động nhận diện và tải thêm các component phụ thuộc nếu cần.*
20
-
21
- ### 3. Cấu hình Tailwind
22
- Chạy lệnh sau để nhận hướng dẫn copy-paste cấu hình theme:
23
- ```bash
24
- npx cus-base-ui tailwind
25
- ```
26
-
27
- ---
28
- ### 4. Liệt Component
29
- ```bash
30
- npx cus-base-ui list
31
- ```
32
-
33
- ## 🛠 Cách để tự bạn quản lý và phát hành
34
-
35
- ### 1. Cập nhật Registry (Khi thêm component mới)
36
- ```bash
37
- npm run registry:build
38
- ```
39
- Sau đó hãy `git commit` và `git push` lên GitHub để CLI trên máy người dùng có thể thấy update mới.
40
-
41
- ### 2. Biên dịch CLI
42
- ```bash
43
- npm run build:cli
44
- ```
45
-
46
- ### 3. Phát hành lên NPM
47
- Để mọi người có thể gõ `npx cus-base-ui`, bạn cần đưa nó lên NPM:
48
- 1. Đăng nhập: `npm login`
49
- 2. Phát hành: `npm publish` (Nếu tên `cus-base-ui` đã bị trùng trên NPM, hãy đổi tên trong `package.json`).
50
-
51
- ---
52
-
53
- ## 📂 Cơ chế hoạt động
54
- - **Local Mode**: Nếu bạn chạy `npx cus-base-ui add --local`, nó sẽ tìm file `registry.json` ngay tại thư mục hiện tại.
55
- - **Remote Mode (Mặc định)**: CLI sẽ tải dữ liệu trực tiếp từ: `https://raw.githubusercontent.com/huy14032003/ui-component/main/registry.json`.
1
+ # cus-base-ui
2
+
3
+ Bộ component UI cho React, phân phối qua CLI copy trực tiếp vào dự án của bạn, không cần cài như package dependency (tương tự shadcn/ui).
4
+
5
+ ---
6
+
7
+ ## Yêu cầu
8
+
9
+ - Node.js 18+
10
+ - Dự án React + Vite + TypeScript
11
+
12
+ ---
13
+
14
+ ## Bắt đầu nhanh
15
+
16
+ ### 1. Khởi tạo dự án
17
+
18
+ Đứng tại thư mục gốc dự án của bạn, chạy:
19
+
20
+ ```bash
21
+ npx cus-base-ui init
22
+ ```
23
+
24
+ Lệnh này tự động thực hiện:
25
+
26
+ | Bước | Nội dung |
27
+ |------|----------|
28
+ | Cài dev packages | `tailwindcss`, `@tailwindcss/vite`, `@vitejs/plugin-react`, `vite-plugin-babel`, `babel-plugin-react-compiler`, `@types/node` |
29
+ | Tạo / cập nhật `vite.config.ts` | Thêm plugin Tailwind, React, React Compiler + alias `@`, `@lib`, `@components`, `@assets`, `@pages`, `@styles` |
30
+ | Cập nhật `tsconfig.json` | Thêm `baseUrl` + `paths` tương ứng với alias trên |
31
+ | Setup Tailwind CSS | Thêm `@import "tailwindcss";` vào `src/index.css` (tạo mới nếu chưa có) |
32
+ | Cài core utilities | `clsx`, `tailwind-merge` + tạo `src/lib/utils/cn.ts` |
33
+
34
+ > Nếu `vite.config.ts` hoặc `tsconfig.json` đã tồn tại và đã có cấu hình, CLI sẽ bỏ qua bước đó — không ghi đè.
35
+
36
+ **Kết quả `vite.config.ts` sau init:**
37
+
38
+ ```ts
39
+ import { defineConfig } from 'vite';
40
+ import tailwindcss from '@tailwindcss/vite';
41
+ import react from '@vitejs/plugin-react';
42
+ import babel from 'vite-plugin-babel';
43
+ import { reactCompilerPreset } from 'babel-plugin-react-compiler';
44
+ import path from 'path';
45
+
46
+ export default defineConfig({
47
+ plugins: [
48
+ tailwindcss(),
49
+ react(),
50
+ babel({ presets: [reactCompilerPreset()] }),
51
+ ],
52
+ resolve: {
53
+ alias: {
54
+ '@': path.resolve(__dirname, './src'),
55
+ '@lib': path.resolve(__dirname, './src/lib'),
56
+ '@components': path.resolve(__dirname, './src/components'),
57
+ '@assets': path.resolve(__dirname, './src/assets'),
58
+ '@pages': path.resolve(__dirname, './src/pages'),
59
+ '@styles': path.resolve(__dirname, './src/styles'),
60
+ },
61
+ },
62
+ });
63
+ ```
64
+
65
+ ---
66
+
67
+ ### 2. Thêm component
68
+
69
+ ```bash
70
+ npx cus-base-ui add button
71
+ npx cus-base-ui add button input switch # nhiều component cùng lúc
72
+ npx cus-base-ui add button --force # ghi đè nếu đã tồn tại
73
+ ```
74
+
75
+ Component được copy thẳng vào `src/components/ui/<name>/`. Các component phụ thuộc lẫn nhau sẽ tự động được kéo theo.
76
+
77
+ ---
78
+
79
+ ### 3. Xóa component
80
+
81
+ ```bash
82
+ npx cus-base-ui remove button
83
+ ```
84
+
85
+ ---
86
+
87
+ ### 4. Liệt kê tất cả component
88
+
89
+ ```bash
90
+ npx cus-base-ui list
91
+ ```
92
+
93
+ ---
94
+
95
+ ### 5. Hướng dẫn cấu hình Tailwind theme
96
+
97
+ ```bash
98
+ npx cus-base-ui tailwind
99
+ ```
100
+
101
+ ---
102
+
103
+ ## Tùy chọn
104
+
105
+ | Flag | Mô tả |
106
+ |------|-------|
107
+ | `--local` | Dùng `registry.json` cục bộ thay vì tải từ remote |
108
+ | `--force` | Ghi đè file đã tồn tại khi `add` |
109
+
110
+ ---
111
+
112
+ ## Dành cho maintainer
113
+
114
+ ### Cập nhật registry (sau khi thêm/sửa component)
115
+
116
+ ```bash
117
+ npm run registry:build
118
+ ```
119
+
120
+ Sau đó commit + push lên GitHub để người dùng nhận được bản mới nhất.
121
+
122
+ ### Build CLI
123
+
124
+ ```bash
125
+ npm run build:cli
126
+ ```
127
+
128
+ Output: `dist/ui-cli.js`
129
+
130
+ ### Phát hành lên NPM
131
+
132
+ ```bash
133
+ npm login
134
+ npm publish
135
+ ```
136
+
137
+ > Nếu tên package bị trùng, đổi `name` trong `package.json` trước khi publish.
138
+
139
+ ---
140
+
141
+ ## Cơ chế hoạt động
142
+
143
+ - **Remote mode (mặc định):** Tải `registry.json` từ `https://raw.githubusercontent.com/huy14032003/ui-component/main/registry.json`
144
+ - **Local mode (`--local`):** Đọc `registry.json` ngay tại thư mục hiện tại
145
+ - Registry chứa source code + danh sách npm dependencies của từng component — CLI đọc rồi copy/install vào dự án target
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "cus-base-ui",
3
3
  "private": false,
4
- "version": "0.2.3",
4
+ "version": "0.2.4",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "cus-base-ui": "./dist/ui-cli.cjs"
package/scripts/ui-cli.ts CHANGED
@@ -56,7 +56,7 @@ const getRegistry = async (isLocal: boolean): Promise<Registry> => {
56
56
  }
57
57
  };
58
58
 
59
- const installNpmPackages = (packages: string[], cwd: string) => {
59
+ const installNpmPackages = (packages: string[], cwd: string, dev = false) => {
60
60
  if (packages.length === 0) return;
61
61
 
62
62
  const pkgJsonPath = path.join(cwd, 'package.json');
@@ -71,13 +71,174 @@ const installNpmPackages = (packages: string[], cwd: string) => {
71
71
  if (toInstall.length === 0) return;
72
72
 
73
73
  log(`Installing: ${toInstall.join(', ')}...`);
74
+ const flag = dev ? '--save-dev' : '--save';
74
75
  try {
75
- execSync(`npm install ${toInstall.join(' ')} --save`, { stdio: 'inherit', cwd });
76
+ execSync(`npm install ${toInstall.join(' ')} ${flag}`, { stdio: 'inherit', cwd });
76
77
  } catch (err) {
77
78
  error(`Failed to install packages: ${toInstall.join(', ')}. ${err instanceof Error ? err.message : ''}`);
78
79
  }
79
80
  };
80
81
 
82
+ const VITE_DEV_PACKAGES = ['tailwindcss', '@tailwindcss/vite', '@vitejs/plugin-react', 'vite-plugin-babel', 'babel-plugin-react-compiler', '@types/node'];
83
+
84
+ const VITE_CONFIG_TEMPLATE = `import { defineConfig } from 'vite';
85
+ import tailwindcss from '@tailwindcss/vite';
86
+ import react from '@vitejs/plugin-react';
87
+ import babel from 'vite-plugin-babel';
88
+ import { reactCompilerPreset } from 'babel-plugin-react-compiler';
89
+ import path from 'path';
90
+
91
+ // https://vite.dev/config/
92
+ export default defineConfig({
93
+ plugins: [
94
+ tailwindcss(),
95
+ react(),
96
+ babel({ presets: [reactCompilerPreset()] }),
97
+ ],
98
+ resolve: {
99
+ alias: {
100
+ '@': path.resolve(__dirname, './src'),
101
+ '@lib': path.resolve(__dirname, './src/lib'),
102
+ '@components': path.resolve(__dirname, './src/components'),
103
+ '@assets': path.resolve(__dirname, './src/assets'),
104
+ '@pages': path.resolve(__dirname, './src/pages'),
105
+ '@styles': path.resolve(__dirname, './src/styles'),
106
+ },
107
+ },
108
+ });
109
+ `;
110
+
111
+ const TSCONFIG_PATHS = {
112
+ '@/*': ['./src/*'],
113
+ '@lib/*': ['./src/lib/*'],
114
+ '@components/*': ['./src/components/*'],
115
+ '@assets/*': ['./src/assets/*'],
116
+ '@pages/*': ['./src/pages/*'],
117
+ '@styles/*': ['./src/styles/*'],
118
+ };
119
+
120
+ const setupViteConfig = (cwd: string) => {
121
+ installNpmPackages(VITE_DEV_PACKAGES, cwd, true);
122
+
123
+ const configTs = path.join(cwd, 'vite.config.ts');
124
+ const configJs = path.join(cwd, 'vite.config.js');
125
+
126
+ if (!fs.existsSync(configTs) && !fs.existsSync(configJs)) {
127
+ fs.writeFileSync(configTs, VITE_CONFIG_TEMPLATE);
128
+ log('Created vite.config.ts with Tailwind + React Compiler setup.');
129
+ return;
130
+ }
131
+
132
+ const existingPath = fs.existsSync(configTs) ? configTs : configJs;
133
+ const content = fs.readFileSync(existingPath, 'utf-8');
134
+
135
+ const missingImports: string[] = [];
136
+ if (!content.includes('@tailwindcss/vite')) missingImports.push("import tailwindcss from '@tailwindcss/vite';");
137
+ if (!content.includes('@vitejs/plugin-react')) missingImports.push("import react from '@vitejs/plugin-react';");
138
+ if (!content.includes('vite-plugin-babel')) missingImports.push("import babel from 'vite-plugin-babel';");
139
+ if (!content.includes('babel-plugin-react-compiler')) missingImports.push("import { reactCompilerPreset } from 'babel-plugin-react-compiler';");
140
+
141
+ const missingPlugins: string[] = [];
142
+ if (!content.includes('tailwindcss()')) missingPlugins.push('tailwindcss()');
143
+ if (!content.includes('react()') && !content.includes('react({')) missingPlugins.push('react()');
144
+ if (!content.includes('reactCompilerPreset')) missingPlugins.push('babel({ presets: [reactCompilerPreset()] })');
145
+
146
+ const hasAlias = content.includes('alias:') || content.includes("'@'") || content.includes('"@"');
147
+
148
+ if (missingImports.length === 0 && missingPlugins.length === 0 && hasAlias) {
149
+ log('vite.config already configured — skipping.');
150
+ return;
151
+ }
152
+
153
+ warn(`${path.basename(existingPath)} exists but is missing required setup. Add the following manually:`);
154
+ if (missingImports.length > 0) {
155
+ console.log('\n // Imports to add:');
156
+ for (const imp of missingImports) console.log(` ${imp}`);
157
+ }
158
+ if (missingPlugins.length > 0) {
159
+ console.log('\n // Plugins to add inside defineConfig({ plugins: [...] }):');
160
+ for (const plugin of missingPlugins) console.log(` ${plugin},`);
161
+ }
162
+ if (!hasAlias) {
163
+ console.log('\n // resolve.alias to add inside defineConfig({}):');
164
+ console.log(" resolve: {");
165
+ console.log(" alias: {");
166
+ console.log(" '@': path.resolve(__dirname, './src'),");
167
+ console.log(" '@lib': path.resolve(__dirname, './src/lib'),");
168
+ console.log(" '@components': path.resolve(__dirname, './src/components'),");
169
+ console.log(" '@assets': path.resolve(__dirname, './src/assets'),");
170
+ console.log(" '@pages': path.resolve(__dirname, './src/pages'),");
171
+ console.log(" '@styles': path.resolve(__dirname, './src/styles'),");
172
+ console.log(" },");
173
+ console.log(" },");
174
+ }
175
+ console.log('');
176
+ };
177
+
178
+ const ensureTailwindCss = (cwd: string) => {
179
+ const candidates = ['src/index.css', 'src/App.css', 'src/main.css'];
180
+ for (const cssFile of candidates) {
181
+ const cssPath = path.join(cwd, cssFile);
182
+ if (fs.existsSync(cssPath)) {
183
+ const content = fs.readFileSync(cssPath, 'utf-8');
184
+ if (!content.includes('@import "tailwindcss"') && !content.includes("@import 'tailwindcss'")) {
185
+ fs.writeFileSync(cssPath, `@import "tailwindcss";\n\n${content}`);
186
+ log(`Added @import "tailwindcss" to ${cssFile}`);
187
+ } else {
188
+ log(`${cssFile} already imports Tailwind — skipping.`);
189
+ }
190
+ return;
191
+ }
192
+ }
193
+ // No CSS file found — create src/index.css
194
+ const srcDir = path.join(cwd, 'src');
195
+ if (!fs.existsSync(srcDir)) fs.mkdirSync(srcDir, { recursive: true });
196
+ fs.writeFileSync(path.join(srcDir, 'index.css'), '@import "tailwindcss";\n');
197
+ log('Created src/index.css with @import "tailwindcss"');
198
+ };
199
+
200
+ const setupTsConfig = (cwd: string) => {
201
+ const candidates = ['tsconfig.app.json', 'tsconfig.json'];
202
+
203
+ for (const candidate of candidates) {
204
+ const configPath = path.join(cwd, candidate);
205
+ if (!fs.existsSync(configPath)) continue;
206
+
207
+ const raw = fs.readFileSync(configPath, 'utf-8');
208
+
209
+ if (raw.includes('"@/*"') || raw.includes("'@/*'")) {
210
+ log(`${candidate} already has path aliases — skipping.`);
211
+ return;
212
+ }
213
+
214
+ try {
215
+ // Strip single-line and block comments before parsing
216
+ const stripped = raw.replace(/\/\/[^\n]*/g, '').replace(/\/\*[\s\S]*?\*\//g, '');
217
+ const parsed = JSON.parse(stripped) as { compilerOptions?: Record<string, unknown> };
218
+ if (!parsed.compilerOptions) parsed.compilerOptions = {};
219
+ parsed.compilerOptions.baseUrl = '.';
220
+ parsed.compilerOptions.paths = TSCONFIG_PATHS;
221
+ fs.writeFileSync(configPath, JSON.stringify(parsed, null, 2));
222
+ log(`Added path aliases to ${candidate}.`);
223
+ } catch {
224
+ warn(`Could not auto-patch ${candidate}. Add these to compilerOptions manually:`);
225
+ console.log('\n "baseUrl": ".",');
226
+ console.log(' "paths": {');
227
+ for (const [alias, targets] of Object.entries(TSCONFIG_PATHS)) {
228
+ console.log(` "${alias}": ["${targets[0]}"],`);
229
+ }
230
+ console.log(' }');
231
+ console.log('');
232
+ }
233
+ return;
234
+ }
235
+
236
+ // No tsconfig found — create a minimal one
237
+ const newConfig = { compilerOptions: { baseUrl: '.', paths: TSCONFIG_PATHS } };
238
+ fs.writeFileSync(path.join(cwd, 'tsconfig.json'), JSON.stringify(newConfig, null, 2));
239
+ log('Created tsconfig.json with path aliases.');
240
+ };
241
+
81
242
  const ensureCore = (registry: { core?: { dependencies: string[]; files: { path: string; content: string }[] } }, cwd: string) => {
82
243
  const core = registry.core;
83
244
  if (!core) return;
@@ -226,6 +387,9 @@ const main = async () => {
226
387
  }
227
388
 
228
389
  case 'init': {
390
+ setupViteConfig(cwd);
391
+ setupTsConfig(cwd);
392
+ ensureTailwindCss(cwd);
229
393
  ensureCore(registry, cwd);
230
394
  log('Initialization complete.');
231
395
  break;