@lark-apaas/miaoda-presets 0.1.0-alpha.10 → 0.1.0-alpha.12

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.
@@ -15,8 +15,8 @@ function createEslintConfig() {
15
15
  return typescript_eslint_1.default.config({ ignores: ['dist', 'node_modules', 'build'] }, {
16
16
  extends: [
17
17
  js_1.default.configs.recommended,
18
- ...typescript_eslint_1.default.configs.recommended,
19
18
  eslint_1.default,
19
+ ...typescript_eslint_1.default.configs.recommended,
20
20
  ],
21
21
  files: ['src/**/*.{ts,tsx}'],
22
22
  languageOptions: {
@@ -1,5 +1,4 @@
1
1
  "use strict";
2
- /* eslint-disable no-undef */
3
2
  /**
4
3
  * play-render 使用的 umd-loader
5
4
  */
@@ -60,9 +59,10 @@ function loadScriptsWithDeps() {
60
59
  const loadingPromise = Promise.all(
61
60
  // Map dependencies to promises
62
61
  script.deps.map(dep => loadWithDeps(dep)))
63
- .then(() =>
64
- // After all dependencies are loaded, load this script
65
- loadScript(script.src))
62
+ .then(() => {
63
+ // After all dependencies are loaded, load this script
64
+ return loadScript(script.src);
65
+ })
66
66
  .then(() => {
67
67
  // Mark as loaded after successful load
68
68
  loaded.add(name);
@@ -24,12 +24,5 @@ exports.default = {
24
24
  // Import 相关检查
25
25
  'import/no-unresolved': 'error', // 检查导入路径是否存在
26
26
  'import/named': 'error', // 检查命名导入是否存在
27
- 'no-restricted-syntax': [
28
- 'error',
29
- {
30
- selector: "CallExpression[callee.object.name='console'][callee.property.name=/^(log|warn|info|debug|trace)$/]",
31
- message: 'Avoid using console.log, console.warn, etc. Use `@byted/spark-framework/logger` instead.',
32
- },
33
- ],
34
27
  },
35
28
  };
@@ -6,11 +6,10 @@ 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
- const { enableReactRrefresh = false, isDev = true } = options;
12
- console.log('isDev:', isDev);
13
- console.log('enableReactRrefresh:', enableReactRrefresh);
12
+ const { enableReactRefresh = false, isDev = true } = options;
14
13
  return {
15
14
  experiments: {
16
15
  css: true,
@@ -63,7 +62,7 @@ function createRecommendRspackConfig(options) {
63
62
  }
64
63
  : {}),
65
64
  development: isDev,
66
- refresh: enableReactRrefresh,
65
+ refresh: enableReactRefresh,
67
66
  },
68
67
  },
69
68
  },
@@ -95,6 +94,10 @@ function createRecommendRspackConfig(options) {
95
94
  new core_1.default.optimize.LimitChunkCountPlugin({
96
95
  maxChunks: 1,
97
96
  }),
97
+ isDev && new RouteParserPlugin({
98
+ appPath: './client/src/app.tsx',
99
+ outputPath: path_1.default.resolve(__dirname, 'dist/client/routes.json'),
100
+ }),
98
101
  ],
99
102
  optimization: isDev ? {} : {
100
103
  moduleIds: 'deterministic',
@@ -41,7 +41,7 @@ function createRecommendTailwindConfig(options) {
41
41
  darkMode: 'class',
42
42
  content: [
43
43
  // 让 framework 里的 tailwind 生效
44
- path.join(path.dirname(require.resolve('@lark-apaas/miaoda-toolkit')), '/**/*.js'),
44
+ path.join(path.dirname(require.resolve('@lark-apaas/client-core')), '/**/*.js'),
45
45
  ],
46
46
  prefix: '',
47
47
  plugins: [],
@@ -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;
@@ -8,14 +8,13 @@ const path_1 = __importDefault(require("path"));
8
8
  const core_1 = __importDefault(require("@rspack/core"));
9
9
  const rspack_1 = require("./recommend/rspack");
10
10
  const webpack_merge_1 = __importDefault(require("webpack-merge"));
11
- // 妙搭template-v3使用的配置构造函数
12
11
  // eslint-disable-next-line max-lines-per-function
13
12
  function createRspackConfig(options) {
14
- const { enableReactRrefresh = false, isDevBuildMode = true } = options;
15
- console.log('isDevBuildMode:', isDevBuildMode);
16
- console.log('enableReactRrefresh:', enableReactRrefresh);
13
+ const { enableReactRefresh = false, isDev = true } = options;
14
+ console.log('isDev:', isDev);
15
+ console.log('enableReactRefresh:', enableReactRefresh);
17
16
  // 构建外部依赖配置,对应vite的rollupOptions.external和globals
18
- const externals = isDevBuildMode
17
+ const externals = isDev
19
18
  ? {
20
19
  antd: 'antd',
21
20
  '@ant-design/icons': 'icons',
@@ -26,11 +25,11 @@ function createRspackConfig(options) {
26
25
  }
27
26
  : {};
28
27
  const recommendConfig = (0, rspack_1.createRecommendRspackConfig)({
29
- enableReactRrefresh,
30
- isDev: isDevBuildMode,
28
+ enableReactRefresh,
29
+ isDev,
31
30
  });
32
31
  return (0, webpack_merge_1.default)(recommendConfig, {
33
- mode: isDevBuildMode ? 'development' : 'production',
32
+ mode: isDev ? 'development' : 'production',
34
33
  entry: './src/index.tsx',
35
34
  output: {
36
35
  publicPath: '/',
@@ -61,7 +60,7 @@ function createRspackConfig(options) {
61
60
  },
62
61
  extensions: ['.js', '.jsx', '.ts', '.tsx', '.json'],
63
62
  },
64
- devServer: isDevBuildMode
63
+ devServer: isDev
65
64
  ? undefined
66
65
  : {
67
66
  host: '::',
@@ -91,46 +90,5 @@ function createRspackConfig(options) {
91
90
  },
92
91
  }),
93
92
  ],
94
- optimization: {
95
- moduleIds: 'deterministic',
96
- concatenateModules: true,
97
- minimize: true, // 对应vite的minify配置
98
- minimizer: [
99
- new core_1.default.SwcJsMinimizerRspackPlugin({
100
- minimizerOptions: {
101
- // 保持不压缩
102
- minify: !isDevBuildMode,
103
- mangle: !isDevBuildMode,
104
- format: {
105
- beautify: isDevBuildMode,
106
- comments: false,
107
- },
108
- compress: {
109
- keep_classnames: true,
110
- keep_fnames: true,
111
- keep_fargs: !isDevBuildMode,
112
- unused: true,
113
- dead_code: true,
114
- drop_debugger: true,
115
- // FIXME: 先临时开始 console.log
116
- // drop_console: !isDevBuildMode,
117
- const_to_let: !isDevBuildMode,
118
- booleans_as_integers: !isDevBuildMode,
119
- booleans: !isDevBuildMode,
120
- // maybe unsafe
121
- reduce_funcs: !isDevBuildMode,
122
- reduce_vars: !isDevBuildMode,
123
- },
124
- },
125
- }),
126
- new core_1.default.LightningCssMinimizerRspackPlugin(),
127
- ],
128
- sideEffects: true,
129
- usedExports: true,
130
- innerGraph: true,
131
- providedExports: true,
132
- mergeDuplicateChunks: true,
133
- splitChunks: false, // 禁用代码分割,保持单文件输出
134
- },
135
93
  });
136
94
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lark-apaas/miaoda-presets",
3
- "version": "0.1.0-alpha.10",
3
+ "version": "0.1.0-alpha.12",
4
4
  "files": [
5
5
  "lib"
6
6
  ],
@@ -14,6 +14,7 @@
14
14
  "@babel/types": "^7.28.2",
15
15
  "@eslint/js": "^9.34.0",
16
16
  "@react-dev-inspector/middleware": "^2.0.1",
17
+ "@rsdoctor/rspack-plugin": "^1.1.8",
17
18
  "@rspack/dev-server": "^1.1.3",
18
19
  "@rspack/plugin-react-refresh": "^1.4.3",
19
20
  "dayjs": "^1.11.14",
@@ -32,6 +33,9 @@
32
33
  "@lark-apaas/miaoda-inspector-jsx-runtime": "0.1.0-alpha.6"
33
34
  },
34
35
  "devDependencies": {
36
+ "@babel/parser": "^7.28.4",
37
+ "@babel/traverse": "^7.28.4",
38
+ "@babel/types": "^7.28.4",
35
39
  "@biomejs/biome": "2.0.6",
36
40
  "@changesets/cli": "^2.29.5",
37
41
  "@rspack/core": "^1.4.4",