@meituan-nocode/vite-plugin-nocode-compiler 0.1.0-beta.10 → 0.1.0-beta.18-z

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.
package/README.md CHANGED
@@ -1,120 +1,203 @@
1
1
  # @meituan-nocode/vite-plugin-nocode-compiler
2
2
 
3
- 一个用于 Vite nocode 编译插件,为 JSX 元素自动添加 nocode 所需的标识属性。
3
+ Vite 插件,用于在构建过程中处理 Vue React 组件,添加 nocode 相关的标记。该插件支持自动检测项目框架类型(Vue/React),并应用相应的编译逻辑。
4
4
 
5
- ## 功能
5
+ ## 特性
6
6
 
7
- - 🚀 **多框架支持**: 支持 JSX、TSXVue 文件
8
- - 📦 **自动元素标记**: 为非 Three.js Fiber 和非 Drei 的元素自动添加 nocode 标识
9
- - 🔄 **数组上下文检测**: 智能识别数组映射,添加索引信息
10
- - 🎯 **简单配置**: 开箱即用,仅需最少配置
11
- - ⚡️ **高性能**: 优化的编译过程,快速处理
7
+ - 支持 VueReact 组件的处理
8
+ - 自动检测项目框架类型
9
+ - 兼容 Vite 4.x 和 5.x 版本
10
+ - 可配置的日志输出
11
+ - 支持 ESM 和 CommonJS 导入方式
12
12
 
13
13
  ## 安装
14
14
 
15
15
  ```bash
16
+ # npm
16
17
  npm install @meituan-nocode/vite-plugin-nocode-compiler --save-dev
18
+
19
+ # yarn
20
+ yarn add @meituan-nocode/vite-plugin-nocode-compiler --dev
21
+
22
+ # pnpm
23
+ pnpm add @meituan-nocode/vite-plugin-nocode-compiler -D
24
+ ```
25
+
26
+ ## 在测试项目中引入和使用
27
+
28
+ ### 1. 安装依赖
29
+
30
+ 首先确保安装了必要的依赖:
31
+
32
+ ```bash
33
+ # 安装 vite-plugin-nocode-compiler
34
+ npm install @meituan-nocode/vite-plugin-nocode-compiler --save-dev
35
+
36
+ # 确保安装了 vite
37
+ npm install vite --save-dev
17
38
  ```
18
39
 
19
- ## 使用
40
+ ### 2. 配置 Vite
20
41
 
21
- ### 基础使用
42
+ 在测试项目的根目录创建或修改 `vite.config.js` 或 `vite.config.ts` 文件:
22
43
 
23
- 在你的 `vite.config.js` `vite.config.ts` 中:
44
+ #### ESM 方式 (推荐)
24
45
 
25
- ```javascript
46
+ ```js
47
+ // vite.config.js / vite.config.ts
26
48
  import { defineConfig } from 'vite';
27
- import { componentCompiler } from '@meituan-nocode/vite-plugin-nocode-compiler';
49
+ import { NocodeCompiler } from '@meituan-nocode/vite-plugin-nocode-compiler';
50
+ // 或者使用默认导出
51
+ // import NocodeCompiler from '@meituan-nocode/vite-plugin-nocode-compiler';
28
52
 
29
53
  export default defineConfig({
30
54
  plugins: [
31
- componentCompiler(), // 使用默认配置
32
- // 其他插件...
55
+ NocodeCompiler({
56
+ enableLogging: true, // 开启日志,方便调试
57
+ }),
33
58
  ],
34
59
  });
35
60
  ```
36
61
 
37
- ### 启用调试日志
62
+ #### CommonJS 方式
63
+
64
+ ```js
65
+ // vite.config.js
66
+ const { defineConfig } = require('vite');
67
+ const { NocodeCompiler } = require('@meituan-nocode/vite-plugin-nocode-compiler');
68
+
69
+ module.exports = defineConfig({
70
+ plugins: [
71
+ NocodeCompiler({
72
+ enableLogging: true, // 开启日志,方便调试
73
+ }),
74
+ ],
75
+ });
76
+ ```
77
+
78
+ ### 3. 运行测试项目
79
+
80
+ 配置完成后,可以通过以下命令启动测试项目:
81
+
82
+ ```bash
83
+ # 开发模式
84
+ npx vite
85
+
86
+ # 或构建
87
+ npx vite build
88
+ ```
89
+
90
+ ### 4. 验证插件是否正常工作
91
+
92
+ 如果启用了 `enableLogging: true`,在构建过程中会看到插件的日志输出,包括检测到的框架类型和处理的文件信息。
93
+
94
+ ## 使用方法详解
38
95
 
39
- 如果需要查看编译过程的详细日志:
96
+ ### ESM 导入 (推荐)
40
97
 
41
- ```javascript
98
+ ```js
99
+ // vite.config.js / vite.config.ts
42
100
  import { defineConfig } from 'vite';
43
- import { componentCompiler } from '@meituan-nocode/vite-plugin-nocode-compiler';
101
+ import { NocodeCompiler } from '@meituan-nocode/vite-plugin-nocode-compiler';
102
+ // 或者使用默认导入
103
+ // import NocodeCompiler from '@meituan-nocode/vite-plugin-nocode-compiler';
44
104
 
45
105
  export default defineConfig({
46
106
  plugins: [
47
- componentCompiler({
48
- enableLogging: true, // 启用调试日志
107
+ NocodeCompiler({
108
+ enableLogging: true,
109
+ // 其他配置选项
49
110
  }),
50
- // 其他插件...
51
111
  ],
52
112
  });
53
113
  ```
54
114
 
55
- ## 工作原理
115
+ ### CommonJS 导入
56
116
 
57
- 插件会扫描 `.jsx`、`.tsx` 和 `.vue` 文件中的元素,对于不在 Three.js Fiber 元素列表和 Drei 元素列表中的元素,自动添加以下属性:
117
+ ```js
118
+ // vite.config.js
119
+ const { defineConfig } = require('vite');
120
+ const { NocodeCompiler } = require('@meituan-nocode/vite-plugin-nocode-compiler');
121
+ // 或者使用默认导入并解构
122
+ // const pkg = require('@meituan-nocode/vite-plugin-nocode-compiler');
123
+ // const { NocodeCompiler } = pkg;
58
124
 
59
- - `data-nocode-id`: 格式为 `文件路径:行号:列号`
60
- - `data-nocode-tag-name`: 元素名称
61
- - `data-nocode-array`: 当元素在数组映射中时,包含数组名称
125
+ module.exports = defineConfig({
126
+ plugins: [
127
+ NocodeCompiler({
128
+ enableLogging: true,
129
+ // 其他配置选项
130
+ }),
131
+ ],
132
+ });
133
+ ```
62
134
 
63
- ## 示例
135
+ ## 配置选项
64
136
 
65
- 输入:
137
+ | 选项 | 类型 | 默认值 | 描述 |
138
+ | --------------- | --------- | ------- | ------------------------------------------------------ |
139
+ | `enableLogging` | `boolean` | `false` | 是否启用日志输出,开启后会输出详细的处理过程和调试信息 |
66
140
 
67
- ```jsx
68
- function App() {
69
- return (
70
- <div>
71
- <button>Click me</button>
72
- {items.map((item, index) => (
73
- <span key={item.id}>{item.name}</span>
74
- ))}
75
- </div>
76
- );
77
- }
78
- ```
141
+ ## 处理的文件类型
79
142
 
80
- 输出:
81
-
82
- ```jsx
83
- function App() {
84
- return (
85
- <div data-nocode-id='App.jsx:3:4' data-nocode-name='div'>
86
- <button data-nocode-id='App.jsx:4:6' data-nocode-name='button'>
87
- Click me
88
- </button>
89
- {items.map((item, index) => (
90
- <span data-nocode-id='App.jsx:6:8' data-nocode-name='span' data-nocode-array='items' data-nocode-index='${index}' key={item.id}>
91
- {item.name}
92
- </span>
93
- ))}
94
- </div>
95
- );
96
- }
97
- ```
143
+ 插件会处理以下文件类型:
98
144
 
99
- ## 架构
145
+ - Vue 文件: `.vue` 文件
146
+ - JSX/TSX 文件: `.jsx`, `.tsx` 文件
147
+ - 包含 JSX 语法的 JS/TS 文件: `.js`, `.ts` 文件
100
148
 
101
- 该插件采用模块化设计,支持多种前端框架:
149
+ ## 依赖关系
102
150
 
103
- - **JSX/TSX**: ✅ 已实现
104
- - **Vue**: ✅ 已实现
151
+ 该插件依赖于 `@meituan-nocode/nocode-compiler-core` 包,它提供了核心的编译逻辑:
105
152
 
106
- 详细架构说明请参考 [ARCHITECTURE.md](./ARCHITECTURE.md)
153
+ - Vue 组件编译器 (`VueCompiler`)
154
+ - JSX 组件编译器 (`JSXCompiler`)
155
+ - 代码转换器 (`CodeTransformer`)
107
156
 
108
- ## 开发
157
+ ## 在 monorepo 项目中使用
109
158
 
110
- ```bash
111
- # 构建
112
- npm run build
159
+ 在 monorepo 项目中,可以在各子项目的 `vite.config.js` 中分别配置插件:
160
+
161
+ ```js
162
+ // 子项目的 vite.config.js
163
+ import { defineConfig } from 'vite';
164
+ import { NocodeCompiler } from '@meituan-nocode/vite-plugin-nocode-compiler';
113
165
 
114
- # 开发模式(监听文件变化)
115
- npm run dev
166
+ export default defineConfig({
167
+ plugins: [
168
+ NocodeCompiler({
169
+ enableLogging: true,
170
+ }),
171
+ ],
172
+ });
116
173
  ```
117
174
 
118
- ## 扩展支持
175
+ ## 常见问题
176
+
177
+ ### Q: 如何确认插件正在正常工作?
178
+
179
+ A: 开启 `enableLogging` 选项,构建时会输出详细的处理日志,包括检测到的框架类型和处理的文件。
180
+
181
+ ### Q: 插件处理哪些文件类型?
182
+
183
+ A: 插件会处理以下文件类型:
184
+
185
+ - Vue 框架: `.vue` 文件
186
+ - React 框架: `.jsx`, `.tsx` 文件,以及包含 JSX 语法的 `.js`, `.ts` 文件
187
+
188
+ ### Q: 如何在 monorepo 项目中使用?
189
+
190
+ A: 在各子项目的 `vite.config.js` 中分别配置插件即可。如果子项目共享配置,确保正确设置相关选项。
191
+
192
+ ### Q: 如何排查插件不工作的问题?
193
+
194
+ A:
195
+
196
+ 1. 确保 `vite.config.js` 中正确导入和配置了插件
197
+ 2. 开启 `enableLogging: true` 查看详细日志
198
+ 3. 检查项目中是否有需要处理的 Vue 或 JSX/TSX 文件
199
+ 4. 确认 Vite 版本兼容性(支持 Vite 4.x 和 5.x)
200
+
201
+ ## 许可证
119
202
 
120
- 如需添加新框架支持,请参考架构文档中的扩展指南。
203
+ MIT
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const m=require("@meituan-nocode/nocode-compiler-core");function f(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const p=f(m),d=[".js",".ts",".mjs",".mts",".jsx",".tsx"],g=["isJsx","isTsx","lang.jsx","lang.tsx"];function j(e){return d.some(t=>e.endsWith(t))}const{CodeTransformer:x}=p;function i(e={}){const t=new x(e);return{name:"vite-plugin-nocode-compiler",enforce:"pre",async transform(n,r){if(r.includes("node_modules"))return null;const[a,u]=r.split("?",2);let o=a;const s=new URLSearchParams(u);let l="";return j(o)||o.endsWith(".vue")&&(g.some(c=>s.get(c)!==null)||s.get("lang")==="tsx"||s.get("lang")==="jsx")?l="jsx":(o.endsWith(".html")&&s.get("type")==="template"&&s.has("vue")||o.endsWith(".vue")&&s.get("type")!=="style"&&s.get("raw")===null)&&(l="vue"),l?t.transformCode({content:n,filePath:o,fileType:l}):n}}}exports.NocodeCompiler=i;exports.default=i;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,14 @@
1
- import type { Plugin } from 'vite';
2
1
  export interface NocodeCompilerOptions {
3
2
  enableLogging?: boolean;
4
3
  }
5
- export declare function componentCompiler(options?: NocodeCompilerOptions): Plugin;
4
+ /**
5
+ * Vite插件
6
+ * 用于在构建过程中处理Vue和React组件,添加nocode相关的标记
7
+ * 兼容 Vite 4.x 和 5.x 版本
8
+ */
9
+ export declare function NocodeCompiler(options?: NocodeCompilerOptions): {
10
+ name: string;
11
+ enforce: "pre";
12
+ transform(code: string, id: string): Promise<string | null>;
13
+ };
14
+ export default NocodeCompiler;
@@ -0,0 +1,30 @@
1
+ import * as u from "@meituan-nocode/nocode-compiler-core";
2
+ const c = [".js", ".ts", ".mjs", ".mts", ".jsx", ".tsx"], f = ["isJsx", "isTsx", "lang.jsx", "lang.tsx"];
3
+ function p(n) {
4
+ return c.some((r) => n.endsWith(r));
5
+ }
6
+ const { CodeTransformer: x } = u;
7
+ function d(n = {}) {
8
+ const r = new x(n);
9
+ return {
10
+ name: "vite-plugin-nocode-compiler",
11
+ enforce: "pre",
12
+ async transform(o, l) {
13
+ if (l.includes("node_modules"))
14
+ return null;
15
+ const [i, a] = l.split("?", 2);
16
+ let t = i;
17
+ const e = new URLSearchParams(a);
18
+ let s = "";
19
+ return p(t) || t.endsWith(".vue") && (f.some((m) => e.get(m) !== null) || e.get("lang") === "tsx" || e.get("lang") === "jsx") ? s = "jsx" : (t.endsWith(".html") && e.get("type") === "template" && e.has("vue") || t.endsWith(".vue") && e.get("type") !== "style" && e.get("raw") === null) && (s = "vue"), s ? r.transformCode({
20
+ content: o,
21
+ filePath: t,
22
+ fileType: s
23
+ }) : o;
24
+ }
25
+ };
26
+ }
27
+ export {
28
+ d as NocodeCompiler,
29
+ d as default
30
+ };
package/dist/index.js CHANGED
@@ -1,28 +1,100 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.componentCompiler = componentCompiler;
4
- const nocode_compiler_core_1 = require("@meituan-nocode/nocode-compiler-core");
5
- function componentCompiler(options = {}) {
6
- const { enableLogging = false } = options;
36
+ exports.NocodeCompiler = NocodeCompiler;
37
+ // import { Plugin } from 'vite';
38
+ // 使用动态导入方式解决 ESM CommonJS 的兼容性问题
39
+ const compilerCore = __importStar(require("@meituan-nocode/nocode-compiler-core"));
40
+ const { CodeTransformer } = compilerCore;
41
+ const utils_1 = require("./utils");
42
+ // 检查是否安装了@vue/compiler-dom
43
+ let vueCompilerAvailable = false;
44
+ try {
45
+ require('@vue/compiler-dom');
46
+ vueCompilerAvailable = true;
47
+ }
48
+ catch (error) {
49
+ console.warn('[vite-plugin-nocode-compiler] @vue/compiler-dom not found. Vue compilation will be skipped.');
50
+ }
51
+ /**
52
+ * Vite插件
53
+ * 用于在构建过程中处理Vue和React组件,添加nocode相关的标记
54
+ * 兼容 Vite 4.x 和 5.x 版本
55
+ */
56
+ function NocodeCompiler(options = {}) {
57
+ // 创建代码转换器实例
58
+ const codeTransformer = new CodeTransformer(options);
7
59
  return {
8
60
  name: 'vite-plugin-nocode-compiler',
9
61
  enforce: 'pre',
10
62
  async transform(code, id) {
11
- // 检查文件是否在 node_modules
63
+ // 跳过node_modules
12
64
  if (id.includes('node_modules')) {
13
- return code;
65
+ return null;
14
66
  }
15
- // 检查文件扩展名
16
- if (!/\.(jsx?|tsx?)$/.test(id)) {
67
+ const [_completePath, query] = id.split('?', 2); // 当前文件的绝对路径
68
+ let filePath = _completePath;
69
+ const params = new URLSearchParams(query);
70
+ let fileType = '';
71
+ if ((0, utils_1.isJsTypeFile)(filePath) || (filePath.endsWith('.vue') && (utils_1.jsxParamList.some(param => params.get(param) !== null) || params.get('lang') === 'tsx' || params.get('lang') === 'jsx'))) {
72
+ // jsx 代码
73
+ fileType = 'jsx';
74
+ }
75
+ else if (filePath.endsWith('.html') && params.get('type') === 'template' && params.has('vue')) {
76
+ // <template src="xxx.html"></template>
77
+ fileType = 'vue';
78
+ }
79
+ else if (filePath.endsWith('.vue') && params.get('type') !== 'style' && params.get('raw') === null) {
80
+ // vue 代码
81
+ fileType = 'vue';
82
+ }
83
+ // 如果是Vue文件但@vue/compiler-dom不可用,跳过处理
84
+ if (fileType === 'vue' && !vueCompilerAvailable) {
85
+ console.warn(`[vite-plugin-nocode-compiler] Skipping Vue file processing for ${filePath} due to missing @vue/compiler-dom`);
17
86
  return code;
18
87
  }
19
- // 使用 jsxcompiler 编译
20
- const jsxCompiler = new nocode_compiler_core_1.JSXCompiler({
21
- enableLogging: enableLogging || false,
22
- rootPath: process.cwd(),
23
- });
24
- const result = jsxCompiler.compile(code, id);
25
- return result;
88
+ if (fileType) {
89
+ return codeTransformer.transformCode({
90
+ content: code,
91
+ filePath,
92
+ fileType,
93
+ });
94
+ }
95
+ return code;
26
96
  },
27
97
  };
28
98
  }
99
+ // 添加默认导出,使 ESM 导入更方便
100
+ exports.default = NocodeCompiler;
@@ -0,0 +1,3 @@
1
+ export declare const JsFileExtList: string[];
2
+ export declare const jsxParamList: string[];
3
+ export declare function isJsTypeFile(file: string): boolean;
package/dist/utils.js ADDED
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.jsxParamList = exports.JsFileExtList = void 0;
4
+ exports.isJsTypeFile = isJsTypeFile;
5
+ exports.JsFileExtList = ['.js', '.ts', '.mjs', '.mts', '.jsx', '.tsx'];
6
+ exports.jsxParamList = ['isJsx', 'isTsx', 'lang.jsx', 'lang.tsx'];
7
+ // 是否为 JS 类型的文件
8
+ function isJsTypeFile(file) {
9
+ return exports.JsFileExtList.some(ext => file.endsWith(ext));
10
+ }
package/package.json CHANGED
@@ -1,10 +1,18 @@
1
1
  {
2
2
  "name": "@meituan-nocode/vite-plugin-nocode-compiler",
3
- "version": "0.1.0-beta.10",
3
+ "version": "0.1.0-beta.18-z",
4
4
  "description": "nocode compiler plugin",
5
- "main": "dist/index.js",
6
- "module": "dist/index.mjs",
5
+ "type": "module",
6
+ "main": "dist/index.cjs.js",
7
+ "module": "dist/index.es.js",
7
8
  "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "require": "./dist/index.cjs.js",
12
+ "import": "./dist/index.es.js",
13
+ "types": "./dist/index.d.ts"
14
+ }
15
+ },
8
16
  "files": [
9
17
  "dist"
10
18
  ],
@@ -13,15 +21,12 @@
13
21
  "build": "tsc",
14
22
  "prepublishOnly": "npm run build"
15
23
  },
16
- "peerDependencies": {
17
- "vite": "^5.4.0"
18
- },
19
24
  "devDependencies": {
20
25
  "@types/node": "^20.0.0",
21
26
  "typescript": "^5.0.0",
22
- "vite": "^5.4.0"
27
+ "vite": "^4.5.14"
23
28
  },
24
29
  "dependencies": {
25
- "@meituan-nocode/nocode-compiler-core": "0.1.0-beta.17"
30
+ "@meituan-nocode/nocode-compiler-core": "0.1.0-beta.18-z"
26
31
  }
27
32
  }
@@ -1,13 +0,0 @@
1
- export type FrameworkType = 'vue' | 'react';
2
- /**
3
- * 框架检测器
4
- * 按优先级检测项目使用的前端框架
5
- * 1. 首先检查是否强制指定了框架
6
- * 2. 然后检查package.json中的依赖(React依赖优先于Vue依赖)
7
- * 3. 接着检查src目录下是否有框架特定文件(JSX/TSX文件优先于Vue文件)
8
- * 4. 如果以上都没有检测到,默认返回React
9
- */
10
- export declare function detectFramework(options?: {
11
- forceFramework?: FrameworkType;
12
- enableLogging?: boolean;
13
- }): FrameworkType;
@@ -1,85 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.detectFramework = detectFramework;
7
- const fs_1 = __importDefault(require("fs"));
8
- const path_1 = __importDefault(require("path"));
9
- /**
10
- * 框架检测器
11
- * 按优先级检测项目使用的前端框架
12
- * 1. 首先检查是否强制指定了框架
13
- * 2. 然后检查package.json中的依赖(React依赖优先于Vue依赖)
14
- * 3. 接着检查src目录下是否有框架特定文件(JSX/TSX文件优先于Vue文件)
15
- * 4. 如果以上都没有检测到,默认返回React
16
- */
17
- function detectFramework(options) {
18
- const log = (message, ...args) => {
19
- if (options?.enableLogging) {
20
- console.log(`[vite-nocode-compiler] ${message}`, ...args);
21
- }
22
- };
23
- // 1. 如果强制指定了框架,直接返回
24
- if (options?.forceFramework) {
25
- log('Using forced framework:', options.forceFramework);
26
- return options.forceFramework;
27
- }
28
- try {
29
- // 2. 检查package.json
30
- const packagePath = path_1.default.resolve(process.cwd(), 'package.json');
31
- log('Checking package.json:', packagePath);
32
- if (fs_1.default.existsSync(packagePath)) {
33
- try {
34
- const pkg = JSON.parse(fs_1.default.readFileSync(packagePath, 'utf8'));
35
- const deps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) };
36
- log('Package dependencies:', deps);
37
- // React相关依赖(优先检查React,因为Vue项目可能也会依赖React组件)
38
- if (deps.react || deps['react-dom']) {
39
- log('React dependency detected');
40
- return 'react';
41
- }
42
- // Vue相关依赖
43
- if (deps.vue || deps['@vue/cli-service'] || deps.nuxt || deps['@vitejs/plugin-vue']) {
44
- log('Vue dependency detected');
45
- return 'vue';
46
- }
47
- }
48
- catch (e) {
49
- log('Failed to parse package.json:', e);
50
- // 解析package.json失败,继续下一步检测
51
- }
52
- }
53
- // 3. 快速检查src目录下是否有框架特定文件(不递归)
54
- const srcDir = path_1.default.resolve(process.cwd(), 'src');
55
- log('Checking src directory:', srcDir);
56
- if (fs_1.default.existsSync(srcDir)) {
57
- try {
58
- const files = fs_1.default.readdirSync(srcDir);
59
- log('Files in src directory:', files);
60
- // 检查是否有.jsx/.tsx文件(优先检查React文件)
61
- if (files.some(file => file.endsWith('.jsx') || file.endsWith('.tsx'))) {
62
- log('JSX/TSX file detected');
63
- return 'react';
64
- }
65
- // 检查是否有.vue文件
66
- if (files.some(file => file.endsWith('.vue'))) {
67
- log('Vue file detected');
68
- return 'vue';
69
- }
70
- }
71
- catch (e) {
72
- log('Failed to read src directory:', e);
73
- // 读取目录失败,继续使用默认值
74
- }
75
- }
76
- // 4. 默认返回React
77
- log('No framework detected, using default: react');
78
- return 'react';
79
- }
80
- catch (e) {
81
- log('Error in detectFramework:', e);
82
- // 出现任何错误,默认使用React
83
- return 'react';
84
- }
85
- }