@lark-apaas/miaoda-presets 0.1.0-alpha.1 → 0.1.0-alpha.11

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.
@@ -13,7 +13,11 @@ const eslint_1 = __importDefault(require("./recommend/eslint"));
13
13
  const importPlugin = require('eslint-plugin-import');
14
14
  function createEslintConfig() {
15
15
  return typescript_eslint_1.default.config({ ignores: ['dist', 'node_modules', 'build'] }, {
16
- extends: [js_1.default.configs.recommended, eslint_1.default, ...typescript_eslint_1.default.configs.recommended],
16
+ extends: [
17
+ js_1.default.configs.recommended,
18
+ eslint_1.default,
19
+ ...typescript_eslint_1.default.configs.recommended,
20
+ ],
17
21
  files: ['src/**/*.{ts,tsx}'],
18
22
  languageOptions: {
19
23
  ecmaVersion: 2020,
@@ -58,7 +58,7 @@ function loadScriptsWithDeps() {
58
58
  // Create loading promise for this script
59
59
  const loadingPromise = Promise.all(
60
60
  // Map dependencies to promises
61
- script.deps.map((dep) => loadWithDeps(dep)))
61
+ script.deps.map(dep => loadWithDeps(dep)))
62
62
  .then(() => {
63
63
  // After all dependencies are loaded, load this script
64
64
  return loadScript(script.src);
@@ -73,7 +73,7 @@ function loadScriptsWithDeps() {
73
73
  return loadingPromise;
74
74
  }
75
75
  // Load all scripts
76
- return Promise.all(Object.keys(scripts).map((name) => loadWithDeps(name)));
76
+ return Promise.all(Object.keys(scripts).map(name => loadWithDeps(name)));
77
77
  }
78
78
  // Start loading all scripts
79
79
  window.__FEISUDA_SCRIPTS_LOADED__ = loadScriptsWithDeps();
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.createRecommendRspackConfig = createRecommendRspackConfig;
7
7
  const path_1 = __importDefault(require("path"));
8
8
  const core_1 = __importDefault(require("@rspack/core"));
9
+ const RouteParserPlugin = require('../rspack-plugins/route-parser-plugin');
9
10
  // eslint-disable-next-line max-lines-per-function
10
11
  function createRecommendRspackConfig(options) {
11
12
  const { enableReactRrefresh = false, isDev = true } = options;
@@ -59,7 +60,7 @@ function createRecommendRspackConfig(options) {
59
60
  runtime: 'automatic',
60
61
  ...(isDev
61
62
  ? {
62
- importSource: path_1.default.dirname(require.resolve('@apaas-ai/miaoda-inspector-jsx-runtime')),
63
+ importSource: path_1.default.dirname(require.resolve('@lark-apaas/miaoda-inspector-jsx-runtime')),
63
64
  }
64
65
  : {}),
65
66
  development: isDev,
@@ -69,7 +70,9 @@ function createRecommendRspackConfig(options) {
69
70
  },
70
71
  },
71
72
  },
72
- ...(isDev ? [require.resolve('@apaas-ai/miaoda-inspector-babel-plugin')] : []),
73
+ ...(isDev
74
+ ? [require.resolve('@lark-apaas/miaoda-inspector-babel-plugin')]
75
+ : []),
73
76
  ],
74
77
  },
75
78
  ],
@@ -93,8 +96,12 @@ function createRecommendRspackConfig(options) {
93
96
  new core_1.default.optimize.LimitChunkCountPlugin({
94
97
  maxChunks: 1,
95
98
  }),
99
+ isDev && new RouteParserPlugin({
100
+ appPath: './client/src/app.tsx',
101
+ outputPath: path_1.default.resolve(__dirname, 'dist/client/routes.json'),
102
+ }),
96
103
  ],
97
- optimization: {
104
+ optimization: isDev ? {} : {
98
105
  moduleIds: 'deterministic',
99
106
  concatenateModules: true,
100
107
  minimize: true, // 对应vite的minify配置
@@ -0,0 +1,275 @@
1
+ "use strict";
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const crypto = require('crypto');
5
+ const { parse } = require('@babel/parser');
6
+ const traverse = require('@babel/traverse').default;
7
+ const t = require('@babel/types');
8
+ class RouteParserPlugin {
9
+ constructor(options = {}) {
10
+ this.options = {
11
+ appPath: options.appPath || './client/src/app.tsx',
12
+ outputPath: options.outputPath || './dist/client/routes.json',
13
+ ...options
14
+ };
15
+ // 缓存相关属性 - 直接存储在实例上
16
+ this.lastAppPathHash = null;
17
+ this.cachedRoutes = null;
18
+ }
19
+ // 统一的日志函数
20
+ log(level, message, ...args) {
21
+ const prefix = '[route-parser]';
22
+ const logMessage = `${prefix} ${message}`;
23
+ switch (level) {
24
+ case 'log':
25
+ console.log(logMessage, ...args);
26
+ break;
27
+ case 'warn':
28
+ console.warn(logMessage, ...args);
29
+ break;
30
+ case 'error':
31
+ console.error(logMessage, ...args);
32
+ break;
33
+ case 'info':
34
+ console.info(logMessage, ...args);
35
+ break;
36
+ default:
37
+ console.log(logMessage, ...args);
38
+ }
39
+ }
40
+ apply(compiler) {
41
+ const pluginName = 'RouteParserPlugin';
42
+ compiler.hooks.emit.tapAsync(pluginName, (compilation, callback) => {
43
+ try {
44
+ // 检查是否需要重新生成路由
45
+ if (this.shouldRegenerateRoutes()) {
46
+ const routes = this.parseRoutes();
47
+ this.cachedRoutes = routes;
48
+ }
49
+ const routesJson = JSON.stringify(this.cachedRoutes, null, 2);
50
+ // 将 routes.json 添加到编译输出中
51
+ compilation.assets['routes.json'] = {
52
+ source: () => routesJson,
53
+ size: () => routesJson.length
54
+ };
55
+ callback();
56
+ }
57
+ catch (error) {
58
+ this.log('warn', '⚠️ 路由解析失败,使用默认路由:', error.message);
59
+ // 解析失败时使用默认路由
60
+ const defaultRoutes = [{ path: '/' }];
61
+ const routesJson = JSON.stringify(defaultRoutes, null, 2);
62
+ compilation.assets['routes.json'] = {
63
+ source: () => routesJson,
64
+ size: () => routesJson.length
65
+ };
66
+ callback();
67
+ }
68
+ });
69
+ }
70
+ shouldRegenerateRoutes() {
71
+ try {
72
+ const appFilePath = path.resolve(process.cwd(), this.options.appPath);
73
+ if (!fs.existsSync(appFilePath)) {
74
+ this.log('warn', `⚠️ App.tsx 文件不存在: ${appFilePath}`);
75
+ return false;
76
+ }
77
+ // 计算当前文件的哈希值
78
+ const currentHash = this.calculateFileHash(appFilePath);
79
+ // 检查内存中的缓存
80
+ if (this.lastAppPathHash === currentHash && this.cachedRoutes) {
81
+ return false; // 不需要重新生成
82
+ }
83
+ this.lastAppPathHash = currentHash;
84
+ return true; // 需要重新生成
85
+ }
86
+ catch (error) {
87
+ this.log('warn', '⚠️ 检查文件变更时出错:', error.message);
88
+ return true; // 出错时重新生成
89
+ }
90
+ }
91
+ calculateFileHash(filePath) {
92
+ try {
93
+ const content = fs.readFileSync(filePath, 'utf-8');
94
+ return crypto.createHash('md5').update(content).digest('hex');
95
+ }
96
+ catch (error) {
97
+ this.log('warn', '⚠️ 计算文件哈希失败:', error.message);
98
+ return null;
99
+ }
100
+ }
101
+ parseRoutes() {
102
+ try {
103
+ const appFilePath = path.resolve(process.cwd(), this.options.appPath);
104
+ if (!fs.existsSync(appFilePath)) {
105
+ throw new Error(`App.tsx 文件不存在: ${appFilePath}`);
106
+ }
107
+ const sourceCode = fs.readFileSync(appFilePath, 'utf-8');
108
+ // 解析 TypeScript/JSX 代码
109
+ const ast = parse(sourceCode, {
110
+ sourceType: 'module',
111
+ plugins: [
112
+ 'jsx',
113
+ 'typescript',
114
+ 'decorators-legacy',
115
+ 'classProperties',
116
+ 'objectRestSpread',
117
+ 'functionBind',
118
+ 'exportDefaultFrom',
119
+ 'exportNamespaceFrom',
120
+ 'dynamicImport',
121
+ 'nullishCoalescingOperator',
122
+ 'optionalChaining'
123
+ ]
124
+ });
125
+ // 使用 Set 来存储路径,自动去重
126
+ const routeSet = new Set();
127
+ // 用于跟踪路由嵌套
128
+ const routeStack = [];
129
+ const self = this;
130
+ traverse(ast, {
131
+ JSXElement: {
132
+ enter(path) {
133
+ const { openingElement } = path.node;
134
+ // 检查是否是 Route 组件
135
+ if (self.isRouteComponent(openingElement)) {
136
+ const routeInfo = self.extractRouteInfo(openingElement);
137
+ // 将当前路由信息推入堆栈
138
+ routeStack.push(routeInfo);
139
+ }
140
+ },
141
+ exit(path) {
142
+ const { openingElement } = path.node;
143
+ // 当离开 Route 元素时,从堆栈中弹出
144
+ if (self.isRouteComponent(openingElement)) {
145
+ const currentRoute = routeStack.pop();
146
+ // 跳过通配符路径
147
+ if (currentRoute && currentRoute.path === '*') {
148
+ return;
149
+ }
150
+ // 如果有路径或是索引路由
151
+ if (currentRoute && (currentRoute.path || currentRoute.index)) {
152
+ const fullPath = self.buildFullPath(routeStack, currentRoute);
153
+ if (fullPath) {
154
+ routeSet.add(fullPath);
155
+ }
156
+ }
157
+ }
158
+ }
159
+ }
160
+ });
161
+ // 将 Set 转换为数组返回
162
+ const routes = Array.from(routeSet).map(routePath => ({ path: routePath }));
163
+ return routes.length > 0 ? routes : [{ path: '/' }];
164
+ }
165
+ catch (error) {
166
+ // 如果解析失败,返回默认路由
167
+ this.log('warn', '⚠️ 路由解析失败,使用默认路由:', error.message);
168
+ return [{ path: '/' }];
169
+ }
170
+ }
171
+ isRouteComponent(openingElement) {
172
+ return (t.isJSXIdentifier(openingElement.name) &&
173
+ openingElement.name.name === 'Route');
174
+ }
175
+ isRoutesComponent(path) {
176
+ const openingElement = path.node.openingElement;
177
+ return (t.isJSXIdentifier(openingElement.name) &&
178
+ openingElement.name.name === 'Routes');
179
+ }
180
+ extractRouteInfo(openingElement) {
181
+ const routeInfo = {};
182
+ // 提取所有属性
183
+ openingElement.attributes.forEach((attr) => {
184
+ if (t.isJSXAttribute(attr)) {
185
+ const { name } = attr.name;
186
+ let value;
187
+ // 处理不同类型的属性值
188
+ if (attr.value) {
189
+ if (t.isStringLiteral(attr.value)) {
190
+ value = attr.value.value;
191
+ }
192
+ else if (t.isJSXExpressionContainer(attr.value)) {
193
+ const expression = attr.value.expression;
194
+ if (t.isStringLiteral(expression)) {
195
+ value = expression.value;
196
+ }
197
+ else if (t.isTemplateLiteral(expression)) {
198
+ // 处理模板字符串
199
+ value = this.evaluateTemplateLiteral(expression);
200
+ }
201
+ else {
202
+ // 对于其他表达式,设为 true
203
+ value = true;
204
+ }
205
+ }
206
+ }
207
+ else {
208
+ // 对于没有值的属性(如 index),设为 true
209
+ value = true;
210
+ }
211
+ routeInfo[name] = value;
212
+ }
213
+ });
214
+ return routeInfo;
215
+ }
216
+ getJSXAttribute(element, name) {
217
+ return element.attributes.find(attr => t.isJSXAttribute(attr) &&
218
+ t.isJSXIdentifier(attr.name) &&
219
+ attr.name.name === name);
220
+ }
221
+ buildFullPath(routeStack, currentRoute) {
222
+ // 构建完整路径
223
+ let fullPath = '';
224
+ // 遍历堆栈中的所有父路由
225
+ for (let i = 0; i < routeStack.length; i++) {
226
+ if (routeStack[i].path) {
227
+ // 确保路径格式正确(开头有/,结尾没有/)
228
+ let parentPath = routeStack[i].path;
229
+ if (!parentPath.startsWith('/'))
230
+ parentPath = `/${parentPath}`;
231
+ if (parentPath.endsWith('/') && parentPath !== '/') {
232
+ parentPath = parentPath.slice(0, -1);
233
+ }
234
+ fullPath += parentPath === '/' ? '' : parentPath;
235
+ }
236
+ }
237
+ // 添加当前路由的路径
238
+ if (currentRoute.index) {
239
+ // 索引路由使用父路由的路径
240
+ return fullPath || '/';
241
+ }
242
+ else if (currentRoute.path) {
243
+ const routePath = currentRoute.path;
244
+ // 跳过通配符路径
245
+ if (routePath === '*') {
246
+ return null;
247
+ }
248
+ // 处理相对路径(不以/开头的路径)
249
+ if (!routePath.startsWith('/')) {
250
+ fullPath = `${fullPath}/${routePath}`;
251
+ }
252
+ else {
253
+ fullPath = routePath; // 绝对路径覆盖父路径
254
+ }
255
+ // 确保路径格式正确
256
+ if (fullPath === '')
257
+ fullPath = '/';
258
+ if (!fullPath.startsWith('/'))
259
+ fullPath = `/${fullPath}`;
260
+ return fullPath;
261
+ }
262
+ return null;
263
+ }
264
+ evaluateTemplateLiteral(templateLiteral) {
265
+ // 简单处理模板字符串,这里主要处理 `*` 这种情况
266
+ const quasis = templateLiteral.quasis;
267
+ const expressions = templateLiteral.expressions;
268
+ if (quasis.length === 1 && expressions.length === 0) {
269
+ return quasis[0].value.raw;
270
+ }
271
+ // 对于复杂的模板字符串,返回原始字符串
272
+ return quasis.map(q => q.value.raw).join('');
273
+ }
274
+ }
275
+ module.exports = RouteParserPlugin;
@@ -24,7 +24,10 @@ function createRspackConfig(options) {
24
24
  echarts: 'echarts',
25
25
  }
26
26
  : {};
27
- const recommendConfig = (0, rspack_1.createRecommendRspackConfig)({ enableReactRrefresh, isDev });
27
+ const recommendConfig = (0, rspack_1.createRecommendRspackConfig)({
28
+ enableReactRrefresh,
29
+ isDev,
30
+ });
28
31
  return (0, webpack_merge_1.default)(recommendConfig, {
29
32
  mode: isDev ? 'development' : 'production',
30
33
  entry: './src/index.tsx',
@@ -33,13 +36,15 @@ function createRspackConfig(options) {
33
36
  // path: path.resolve(__dirname, 'dist'),
34
37
  filename: 'assets/index.js',
35
38
  cssFilename: 'assets/index.css',
36
- assetModuleFilename: (pathData) => {
39
+ assetModuleFilename: pathData => {
37
40
  // 对应vite的assetFileNames逻辑
38
41
  const ext = path_1.default.extname(pathData.filename || '');
39
42
  if (ext === '.css') {
40
43
  return 'assets/index.css';
41
44
  }
42
- return pathData.filename ? `assets/${pathData.filename}` : 'assets/asset-[hash][ext]';
45
+ return pathData.filename
46
+ ? `assets/${pathData.filename}`
47
+ : 'assets/asset-[hash][ext]';
43
48
  },
44
49
  library: {
45
50
  type: 'self', // 对应vite的iife格式
@@ -8,7 +8,9 @@ const webpack_merge_1 = __importDefault(require("webpack-merge"));
8
8
  const tailwind_1 = require("./recommend/tailwind");
9
9
  function createTailwindConfig(options) {
10
10
  const { isDevBuildMode = true } = options;
11
- const recommendConfig = (0, tailwind_1.createRecommendTailwindConfig)({ isDev: isDevBuildMode });
11
+ const recommendConfig = (0, tailwind_1.createRecommendTailwindConfig)({
12
+ isDev: isDevBuildMode,
13
+ });
12
14
  return (0, webpack_merge_1.default)(recommendConfig, {
13
15
  content: ['./src/**/*.{ts,tsx}'],
14
16
  });
package/package.json CHANGED
@@ -1,28 +1,13 @@
1
1
  {
2
2
  "name": "@lark-apaas/miaoda-presets",
3
- "version": "0.1.0-alpha.1",
3
+ "version": "0.1.0-alpha.11",
4
4
  "files": [
5
5
  "lib"
6
6
  ],
7
7
  "publishConfig": {
8
8
  "access": "public"
9
9
  },
10
- "scripts": {
11
- "build": "tsc && npm run copy:json",
12
- "copy:json": "cp -r src/*.json lib",
13
- "watch": "tsc --watch",
14
- "bump": "changeset version",
15
- "change": "changeset",
16
- "check": "biome check --write",
17
- "dev": "rslib build --watch",
18
- "format": "biome format --write",
19
- "storybook": "storybook dev",
20
- "test": "echo 0",
21
- "prepublishOnly": "npm run build"
22
- },
23
10
  "dependencies": {
24
- "@lark-apaas/miaoda-inspector-babel-plugin": "workspace:*",
25
- "@lark-apaas/miaoda-inspector-jsx-runtime": "workspace:*",
26
11
  "@babel/core": "^7.28.0",
27
12
  "@babel/parser": "^7.28.0",
28
13
  "@babel/traverse": "^7.28.0",
@@ -43,9 +28,14 @@
43
28
  "tsconfig-paths-webpack-plugin": "^4.2.0",
44
29
  "typescript-eslint": "^8.41.0",
45
30
  "webpack-merge": "^6.0.1",
46
- "tailwindcss": "^4.1.13"
31
+ "tailwindcss": "^4.1.13",
32
+ "@lark-apaas/miaoda-inspector-babel-plugin": "0.1.0-alpha.5",
33
+ "@lark-apaas/miaoda-inspector-jsx-runtime": "0.1.0-alpha.6"
47
34
  },
48
35
  "devDependencies": {
36
+ "@babel/parser": "^7.28.4",
37
+ "@babel/traverse": "^7.28.4",
38
+ "@babel/types": "^7.28.4",
49
39
  "@biomejs/biome": "2.0.6",
50
40
  "@changesets/cli": "^2.29.5",
51
41
  "@rspack/core": "^1.4.4",
@@ -57,5 +47,17 @@
57
47
  "peerDependencies": {
58
48
  "react": ">=16.14.0",
59
49
  "react-dom": ">=16.14.0"
50
+ },
51
+ "scripts": {
52
+ "build": "tsc && npm run copy:json",
53
+ "copy:json": "cp -r src/*.json lib",
54
+ "watch": "tsc --watch",
55
+ "bump": "changeset version",
56
+ "change": "changeset",
57
+ "check": "biome check --write",
58
+ "dev": "rslib build --watch",
59
+ "format": "biome format --write",
60
+ "storybook": "storybook dev",
61
+ "test": "echo 0"
60
62
  }
61
- }
63
+ }