@ikaros-cli/ikaros 1.4.0 → 2.1.0
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/dist/index.d.mts +328 -55
- package/dist/index.mjs +5 -6
- package/package.json +27 -29
- package/readme.md +39 -1
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { LoggerSystem } from "@ikaros-cli/infra-contrlibs";
|
|
2
1
|
import * as _rspack_core0 from "@rspack/core";
|
|
3
|
-
import { DefinePluginOptions, LightningcssLoaderOptions, Loader, ModuleFederationPluginOptions, Plugin } from "@rspack/core";
|
|
2
|
+
import { Configuration, DefinePluginOptions, LightningcssLoaderOptions, Loader, ModuleFederationPluginOptions, Plugin, RuleSetRule, WatchOptions, rspack } from "@rspack/core";
|
|
4
3
|
import * as _rspack_dev_server0 from "@rspack/dev-server";
|
|
5
4
|
import * as https0 from "https";
|
|
6
5
|
|
|
@@ -11,20 +10,87 @@ interface ImportMetaBaseEnv {
|
|
|
11
10
|
/** 路径前缀 */
|
|
12
11
|
BASE?: string;
|
|
13
12
|
/** 平台 */
|
|
14
|
-
PLATFORM:
|
|
13
|
+
PLATFORM: 'web' | 'desktopClient';
|
|
15
14
|
}
|
|
16
|
-
|
|
15
|
+
type ImportMetaEnv = Record<string, any>;
|
|
17
16
|
interface ImportMeta {
|
|
18
17
|
readonly env: Readonly<ImportMetaEnv & ImportMetaBaseEnv>;
|
|
19
18
|
}
|
|
20
19
|
//#endregion
|
|
21
|
-
//#region src/node/compile/base-compile-service.d.ts
|
|
20
|
+
//#region src/node/compile/core/base-compile-service.d.ts
|
|
21
|
+
type PackageJson = {
|
|
22
|
+
name: string;
|
|
23
|
+
version: string;
|
|
24
|
+
};
|
|
22
25
|
/** 命令 */
|
|
23
|
-
declare
|
|
26
|
+
declare enum Command {
|
|
24
27
|
SERVER = "server",
|
|
25
28
|
BUILD = "build",
|
|
26
29
|
}
|
|
27
30
|
/** 命令选项 */
|
|
31
|
+
type CompileOptions = {
|
|
32
|
+
/** 模式 */
|
|
33
|
+
readonly mode?: string;
|
|
34
|
+
/** 平台 */
|
|
35
|
+
readonly platform: ImportMetaBaseEnv['PLATFORM'];
|
|
36
|
+
};
|
|
37
|
+
type CompileServeParame = {
|
|
38
|
+
command: Command;
|
|
39
|
+
options: CompileOptions;
|
|
40
|
+
configFile?: string;
|
|
41
|
+
onBuildStatus?: (status: {
|
|
42
|
+
success: boolean;
|
|
43
|
+
port?: number;
|
|
44
|
+
message?: string;
|
|
45
|
+
}) => void;
|
|
46
|
+
};
|
|
47
|
+
declare abstract class BaseCompileService {
|
|
48
|
+
/** 构建类型 */
|
|
49
|
+
readonly command: Command;
|
|
50
|
+
/** cli上下文空间 */
|
|
51
|
+
readonly context: string;
|
|
52
|
+
/** 选项 */
|
|
53
|
+
readonly options: CompileOptions;
|
|
54
|
+
/** 基于工作目录的Require */
|
|
55
|
+
readonly contextRequire: NodeRequire;
|
|
56
|
+
private _env;
|
|
57
|
+
/** 配置文件 */
|
|
58
|
+
readonly configFile?: string;
|
|
59
|
+
/** env */
|
|
60
|
+
private set env(value);
|
|
61
|
+
get env(): ConfigEnvPre["env"];
|
|
62
|
+
private _contextPkg?;
|
|
63
|
+
/** 用户配置 */
|
|
64
|
+
userConfig?: UserConfig;
|
|
65
|
+
/** 工作目录的 package.json */
|
|
66
|
+
private set contextPkg(value);
|
|
67
|
+
get contextPkg(): PackageJson | undefined;
|
|
68
|
+
/** 是否为electron环境 */
|
|
69
|
+
get isElectron(): boolean;
|
|
70
|
+
constructor(parame: CompileServeParame);
|
|
71
|
+
static create<T extends BaseCompileService, P extends CompileServeParame>(this: new (params: P) => T, params: P): Promise<T>;
|
|
72
|
+
private initialize;
|
|
73
|
+
protected onAfterConfigLoaded(): Promise<void>;
|
|
74
|
+
/** 基于工作目录的定位 */
|
|
75
|
+
protected resolveContext: (...paths: string[]) => string;
|
|
76
|
+
private initContextPkg;
|
|
77
|
+
private initEnv;
|
|
78
|
+
private loadUserConfig;
|
|
79
|
+
/** 检索工作目录的模块路径 */
|
|
80
|
+
protected resolveContextModule(id: string): string | undefined;
|
|
81
|
+
/** 加载模块工作目录的模块 */
|
|
82
|
+
protected loadContextModule<T>(id: string): T;
|
|
83
|
+
/**
|
|
84
|
+
* 获取配置文件
|
|
85
|
+
* @param configFile 配置文件路径
|
|
86
|
+
*/
|
|
87
|
+
protected getUserConfig(): Promise<UserConfig | undefined>;
|
|
88
|
+
protected startCompile(): Promise<void>;
|
|
89
|
+
/** 生命周期抽象方法:dev 启动 */
|
|
90
|
+
protected abstract dev(): unknown | Promise<unknown>;
|
|
91
|
+
/** 生命周期抽象方法:build 启动 */
|
|
92
|
+
protected abstract build(): unknown | Promise<unknown>;
|
|
93
|
+
}
|
|
28
94
|
//#endregion
|
|
29
95
|
//#region src/node/utils/css-loaders-helper.d.ts
|
|
30
96
|
interface CssLoaderOptions {
|
|
@@ -35,10 +101,57 @@ interface CssLoaderOptions {
|
|
|
35
101
|
stylus?: Record<string, any>;
|
|
36
102
|
}
|
|
37
103
|
//#endregion
|
|
38
|
-
//#region src/node/utils/
|
|
104
|
+
//#region src/node/utils/loader-plugin-helper.d.ts
|
|
105
|
+
type ListItemType = RuleSetRule | Plugin;
|
|
39
106
|
type RspackExperiments = {
|
|
40
|
-
import: Record<string,
|
|
107
|
+
import: Record<string, unknown>[];
|
|
41
108
|
};
|
|
109
|
+
type OtherEnv = {
|
|
110
|
+
frameworkEnv?: DefinePluginOptions;
|
|
111
|
+
extEnv?: DefinePluginOptions;
|
|
112
|
+
env?: DefinePluginOptions;
|
|
113
|
+
};
|
|
114
|
+
declare class BaseCreate<T extends ListItemType> {
|
|
115
|
+
protected list: T[];
|
|
116
|
+
protected env: 'development' | 'none' | 'production';
|
|
117
|
+
protected mode: string;
|
|
118
|
+
protected isDev: boolean;
|
|
119
|
+
constructor({
|
|
120
|
+
env,
|
|
121
|
+
mode
|
|
122
|
+
}: {
|
|
123
|
+
env: 'development' | 'none' | 'production';
|
|
124
|
+
mode?: string;
|
|
125
|
+
});
|
|
126
|
+
add(item: T | T[] | undefined): this;
|
|
127
|
+
end(): T[];
|
|
128
|
+
}
|
|
129
|
+
declare class CreateLoader extends BaseCreate<RuleSetRule> {
|
|
130
|
+
constructor({
|
|
131
|
+
env,
|
|
132
|
+
mode
|
|
133
|
+
}: {
|
|
134
|
+
env: 'development' | 'none' | 'production';
|
|
135
|
+
mode?: string;
|
|
136
|
+
});
|
|
137
|
+
private defaultScriptLoader;
|
|
138
|
+
private defaultResourceLoader;
|
|
139
|
+
useDefaultCssLoader(options?: CssLoaderOptions): this;
|
|
140
|
+
useDefaultScriptLoader(options?: RspackExperiments): this;
|
|
141
|
+
useDefaultResourceLoader(): this;
|
|
142
|
+
}
|
|
143
|
+
declare class CreatePlugins extends BaseCreate<Plugin> {
|
|
144
|
+
constructor({
|
|
145
|
+
env,
|
|
146
|
+
mode
|
|
147
|
+
}: {
|
|
148
|
+
env: 'development' | 'none' | 'production';
|
|
149
|
+
mode?: string;
|
|
150
|
+
});
|
|
151
|
+
useDefaultEnvPlugin(otherEnv?: OtherEnv): this;
|
|
152
|
+
useCopyPlugin(): this;
|
|
153
|
+
useHtmlPlugin(templatePath?: string): this;
|
|
154
|
+
}
|
|
42
155
|
type Pages = {
|
|
43
156
|
[key: string]: {
|
|
44
157
|
html: string;
|
|
@@ -47,7 +160,7 @@ type Pages = {
|
|
|
47
160
|
options?: {
|
|
48
161
|
title: string;
|
|
49
162
|
inject: boolean;
|
|
50
|
-
meta: Record<string,
|
|
163
|
+
meta: Record<string, string>;
|
|
51
164
|
};
|
|
52
165
|
};
|
|
53
166
|
};
|
|
@@ -70,11 +183,33 @@ interface CdnPluginOptions {
|
|
|
70
183
|
prodUrl?: string;
|
|
71
184
|
devUrl?: string;
|
|
72
185
|
crossOrigin?: boolean | string;
|
|
73
|
-
sri?: boolean;
|
|
74
|
-
useLocal?: boolean;
|
|
75
186
|
}
|
|
76
187
|
//#endregion
|
|
77
188
|
//#region src/node/user-config.d.ts
|
|
189
|
+
type Bundler = 'rspack' | 'vite';
|
|
190
|
+
interface ElectronConfig {
|
|
191
|
+
main?: {
|
|
192
|
+
entry?: string;
|
|
193
|
+
output?: string;
|
|
194
|
+
plugins?: Plugin | Plugin[];
|
|
195
|
+
loaders?: Loader[];
|
|
196
|
+
};
|
|
197
|
+
preload?: {
|
|
198
|
+
entries?: string[] | Record<string, string>;
|
|
199
|
+
output?: string;
|
|
200
|
+
plugins?: Plugin | Plugin[];
|
|
201
|
+
loaders?: Loader[];
|
|
202
|
+
};
|
|
203
|
+
renderer?: {
|
|
204
|
+
plugins?: Plugin | Plugin[];
|
|
205
|
+
loaders?: Loader[];
|
|
206
|
+
};
|
|
207
|
+
build?: {
|
|
208
|
+
hotReload?: boolean;
|
|
209
|
+
debug?: boolean;
|
|
210
|
+
outDir?: string;
|
|
211
|
+
};
|
|
212
|
+
}
|
|
78
213
|
/**
|
|
79
214
|
* 这里复写了 ModuleFederationPluginOptions,因为 ModuleFederationPluginOptions 是从 module-federation/sdk 导入的,remoteType和rspack的remoteType不一样
|
|
80
215
|
*/
|
|
@@ -82,27 +217,19 @@ interface ModuleFederationOptions extends Omit<ModuleFederationPluginOptions, 'r
|
|
|
82
217
|
remoteType?: 'var' | 'module' | 'assign' | 'this' | 'window' | 'self' | 'global' | 'commonjs' | 'commonjs2' | 'commonjs-module' | 'commonjs-static' | 'amd' | 'amd-require' | 'umd' | 'umd2' | 'jsonp' | 'system' | 'promise' | 'import' | 'script' | 'module-import' | 'node-commonjs';
|
|
83
218
|
}
|
|
84
219
|
interface UserConfig {
|
|
220
|
+
/**
|
|
221
|
+
* 底层打包器
|
|
222
|
+
* - 'rspack': 维持现有行为(默认)
|
|
223
|
+
* - 'vite': 启用 Vite(当前主要用于 Web)
|
|
224
|
+
* @default 'rspack'
|
|
225
|
+
*/
|
|
226
|
+
bundler?: Bundler;
|
|
85
227
|
/**
|
|
86
228
|
* 编译的平台,该值影响底层优化逻辑
|
|
87
229
|
* @default 'pc'
|
|
88
230
|
* @future 该功能受限,目前仅支持 'pc'
|
|
89
231
|
*/
|
|
90
232
|
target?: 'pc' | 'mobile';
|
|
91
|
-
/**
|
|
92
|
-
* 编译的引擎
|
|
93
|
-
* @default 'rspack'
|
|
94
|
-
* @see {@link https://rspack.dev/zh/guide/introduction}
|
|
95
|
-
* @see {@link https://webpack.js.org/}
|
|
96
|
-
* @see {@link https://vitejs.dev/}
|
|
97
|
-
* @warning 该值会影响编译的速度和兼容性,建议使用 rspack
|
|
98
|
-
*/
|
|
99
|
-
engine?: 'rspack' | 'vite';
|
|
100
|
-
/**
|
|
101
|
-
* 编译的平台
|
|
102
|
-
* @default 'web'
|
|
103
|
-
* @description web: 浏览器端 desktop: 桌面端(基于electron)
|
|
104
|
-
*/
|
|
105
|
-
platform?: 'web' | 'desktop';
|
|
106
233
|
/**
|
|
107
234
|
* 页面配置
|
|
108
235
|
* @default
|
|
@@ -115,19 +242,13 @@ interface UserConfig {
|
|
|
115
242
|
*/
|
|
116
243
|
pages?: Pages;
|
|
117
244
|
/**
|
|
118
|
-
*
|
|
119
|
-
*
|
|
245
|
+
* 可选页面启动配置
|
|
246
|
+
* - string[]: 只启动指定的页面
|
|
247
|
+
* - false: 禁用页面选择功能,启动所有页面
|
|
248
|
+
* - undefined: 默认行为,启动所有页面
|
|
249
|
+
* @default undefined
|
|
120
250
|
*/
|
|
121
251
|
enablePages?: string[] | false;
|
|
122
|
-
/**
|
|
123
|
-
* @description 编译时规范检查,一般建议让IDE去做这个工作,关闭该选项以节省构建时间 true:检查错误 false:关闭检查 fix:检查且修复 error:检查错误当出现错误时退出构建
|
|
124
|
-
* @default false
|
|
125
|
-
*/
|
|
126
|
-
eslint?: boolean | 'fix' | 'error';
|
|
127
|
-
/**
|
|
128
|
-
*
|
|
129
|
-
*/
|
|
130
|
-
stylelint?: boolean | 'fix' | 'error';
|
|
131
252
|
/**
|
|
132
253
|
* 全局变量
|
|
133
254
|
* @default {}
|
|
@@ -140,15 +261,26 @@ interface UserConfig {
|
|
|
140
261
|
*/
|
|
141
262
|
moduleFederation?: ModuleFederationOptions | ModuleFederationOptions[];
|
|
142
263
|
/**
|
|
143
|
-
*
|
|
264
|
+
* Rspack 插件(仅 bundler = 'rspack' 时生效)
|
|
144
265
|
* @see {@link https://rspack.dev/zh/guide/features/plugin}
|
|
145
266
|
*/
|
|
146
267
|
plugins?: Plugin | Plugin[];
|
|
147
268
|
/**
|
|
148
|
-
* loader
|
|
269
|
+
* Rspack loader(仅 bundler = 'rspack' 时生效)
|
|
149
270
|
* @see {@link https://rspack.dev/zh/guide/features/loader}
|
|
150
271
|
*/
|
|
151
272
|
loaders?: Loader[];
|
|
273
|
+
/**
|
|
274
|
+
* Vite 配置(仅 bundler = 'vite' 时生效)
|
|
275
|
+
* - 注意:Vite 没有 loader 概念;请通过插件/原生配置实现
|
|
276
|
+
*/
|
|
277
|
+
vite?: {
|
|
278
|
+
/**
|
|
279
|
+
* Vite 插件(仅 bundler = 'vite' 时生效)
|
|
280
|
+
* @see {@link https://vite.dev/guide/api-plugin}
|
|
281
|
+
*/
|
|
282
|
+
plugins?: unknown;
|
|
283
|
+
};
|
|
152
284
|
/**
|
|
153
285
|
* RspackExperiments
|
|
154
286
|
* @default undefined
|
|
@@ -172,11 +304,12 @@ interface UserConfig {
|
|
|
172
304
|
*/
|
|
173
305
|
port?: number;
|
|
174
306
|
/**
|
|
175
|
-
*
|
|
176
|
-
*
|
|
307
|
+
* 服务器代理
|
|
308
|
+
* - rspack 模式:同 @rspack/dev-server
|
|
309
|
+
* - vite 模式:同 Vite server.proxy
|
|
177
310
|
* @default undefined
|
|
178
311
|
*/
|
|
179
|
-
proxy?: _rspack_dev_server0.Configuration['proxy']
|
|
312
|
+
proxy?: _rspack_dev_server0.Configuration['proxy'] | Record<string, string | Record<string, unknown>>;
|
|
180
313
|
/**
|
|
181
314
|
* https
|
|
182
315
|
* @see {@link https://webpack.js.org/configuration/dev-server/#devserverhttps}
|
|
@@ -187,9 +320,9 @@ interface UserConfig {
|
|
|
187
320
|
/**
|
|
188
321
|
* css loader 配置
|
|
189
322
|
* @see {@link lightningcssOptions https://rspack.dev/zh/guide/features/builtin-lightningcss-loader#%E9%80%89%E9%A1%B9}
|
|
190
|
-
* @see {@link https://webpack.js.org/loaders/stylus-loader/#options}
|
|
191
|
-
* @see {@link https://webpack.js.org/loaders/less-loader/#options}
|
|
192
|
-
* @see {@link https://webpack.js.org/loaders/sass-loader/#options}
|
|
323
|
+
* @see {@link stylusOptions https://webpack.js.org/loaders/stylus-loader/#options}
|
|
324
|
+
* @see {@link lessOptions https://webpack.js.org/loaders/less-loader/#options}
|
|
325
|
+
* @see {@link sassOptions https://webpack.js.org/loaders/sass-loader/#options}
|
|
193
326
|
*/
|
|
194
327
|
css?: CssLoaderOptions;
|
|
195
328
|
/**
|
|
@@ -231,12 +364,6 @@ interface UserConfig {
|
|
|
231
364
|
* @default false
|
|
232
365
|
*/
|
|
233
366
|
cache?: boolean;
|
|
234
|
-
/**
|
|
235
|
-
* 默认最大chunk数量
|
|
236
|
-
* @see {@link https://rspack.dev/zh/plugins/webpack/limit-chunk-count-plugin}
|
|
237
|
-
* @default false
|
|
238
|
-
*/
|
|
239
|
-
maxChunks?: false | number;
|
|
240
367
|
/**
|
|
241
368
|
* 是否开启循环依赖检查
|
|
242
369
|
*/
|
|
@@ -255,15 +382,19 @@ interface UserConfig {
|
|
|
255
382
|
/**
|
|
256
383
|
* 默认后缀
|
|
257
384
|
* @see {@link https://webpack.js.org/configuration/resolve/#resolveextensions}
|
|
258
|
-
* @default [
|
|
259
|
-
* @warning 此处将会覆盖默认配置,如果你想保留默认配置添加默认配置即可
|
|
385
|
+
* @default [".js", ".json", ".wasm",'.mjs', '.jsx', '.ts', '.tsx']
|
|
260
386
|
*/
|
|
261
387
|
extensions?: string[];
|
|
262
388
|
};
|
|
389
|
+
/**
|
|
390
|
+
* Electron应用配置
|
|
391
|
+
* @default undefined
|
|
392
|
+
*/
|
|
393
|
+
electron?: ElectronConfig;
|
|
263
394
|
}
|
|
264
395
|
type ConfigEnvPre = Readonly<{
|
|
265
396
|
mode: string;
|
|
266
|
-
env: ImportMeta['env']
|
|
397
|
+
env: Omit<ImportMeta['env'], 'BASE'>;
|
|
267
398
|
command: Command;
|
|
268
399
|
}>;
|
|
269
400
|
type UserConfigFn<C> = (envPre: ConfigEnvPre) => C | Promise<C>;
|
|
@@ -271,4 +402,146 @@ type UserConfigWebExport = UserConfig | Promise<UserConfig> | UserConfigFn<UserC
|
|
|
271
402
|
/** 辅助工具函数 */
|
|
272
403
|
declare const defineConfig: (config: UserConfigWebExport) => UserConfigWebExport;
|
|
273
404
|
//#endregion
|
|
274
|
-
|
|
405
|
+
//#region src/node/compile/web/web-compile-service.d.ts
|
|
406
|
+
declare class WebCompileService extends BaseCompileService {
|
|
407
|
+
private port;
|
|
408
|
+
private viteAdapter?;
|
|
409
|
+
private onBuildStatus?;
|
|
410
|
+
constructor(parame: CompileServeParame);
|
|
411
|
+
protected dev(): Promise<void>;
|
|
412
|
+
protected build(): Promise<void>;
|
|
413
|
+
private prepare;
|
|
414
|
+
getDevPort(): number;
|
|
415
|
+
}
|
|
416
|
+
//#endregion
|
|
417
|
+
//#region src/node/compile/web/resolve-web-preconfig.d.ts
|
|
418
|
+
type WebPreConfig = {
|
|
419
|
+
userConfig?: UserConfig;
|
|
420
|
+
base: string;
|
|
421
|
+
target: Exclude<UserConfig['target'], undefined>;
|
|
422
|
+
pages: Exclude<UserConfig['pages'], undefined>;
|
|
423
|
+
port: number;
|
|
424
|
+
browserslist: string;
|
|
425
|
+
isVue: boolean;
|
|
426
|
+
isReact: boolean;
|
|
427
|
+
};
|
|
428
|
+
//#endregion
|
|
429
|
+
//#region src/node/utils/optional-vite.d.ts
|
|
430
|
+
type OptionalViteAdapter = {
|
|
431
|
+
createWebViteConfig: (params: {
|
|
432
|
+
command: 'server' | 'build';
|
|
433
|
+
mode?: string;
|
|
434
|
+
env: Record<string, unknown>;
|
|
435
|
+
context: string;
|
|
436
|
+
userConfig?: Record<string, unknown>;
|
|
437
|
+
pages: Record<string, {
|
|
438
|
+
html: string;
|
|
439
|
+
entry: string;
|
|
440
|
+
}>;
|
|
441
|
+
base: string;
|
|
442
|
+
port: number;
|
|
443
|
+
isElectron: boolean;
|
|
444
|
+
resolveContext: (...paths: string[]) => string;
|
|
445
|
+
}) => unknown;
|
|
446
|
+
runViteBuild: (config: unknown, options?: {
|
|
447
|
+
onBuildStatus?: (status: {
|
|
448
|
+
success: boolean;
|
|
449
|
+
port?: number;
|
|
450
|
+
message?: string;
|
|
451
|
+
}) => void;
|
|
452
|
+
}) => Promise<string | undefined>;
|
|
453
|
+
startViteDevServer: (config: unknown, options?: {
|
|
454
|
+
port?: number;
|
|
455
|
+
onBuildStatus?: (status: {
|
|
456
|
+
success: boolean;
|
|
457
|
+
port?: number;
|
|
458
|
+
message?: string;
|
|
459
|
+
}) => void;
|
|
460
|
+
}) => Promise<unknown>;
|
|
461
|
+
};
|
|
462
|
+
declare const loadOptionalViteAdapter: (params: {
|
|
463
|
+
loadContextModule: <T>(id: string) => T;
|
|
464
|
+
}) => OptionalViteAdapter;
|
|
465
|
+
//#endregion
|
|
466
|
+
//#region src/node/compile/web/prepare-web-compile.d.ts
|
|
467
|
+
type PrepareWebCompileParams = {
|
|
468
|
+
command: Command;
|
|
469
|
+
options: CompileOptions;
|
|
470
|
+
env: DefinePluginOptions;
|
|
471
|
+
context: string;
|
|
472
|
+
contextPkg?: PackageJson;
|
|
473
|
+
userConfig?: UserConfig;
|
|
474
|
+
isElectron: boolean;
|
|
475
|
+
resolveContext: (...paths: string[]) => string;
|
|
476
|
+
loadViteAdapter?: () => OptionalViteAdapter;
|
|
477
|
+
};
|
|
478
|
+
type PrepareWebCompileResult = {
|
|
479
|
+
bundler: NonNullable<UserConfig['bundler']>;
|
|
480
|
+
config: Configuration | unknown;
|
|
481
|
+
pre: WebPreConfig;
|
|
482
|
+
};
|
|
483
|
+
declare const prepareWebCompile: (params: PrepareWebCompileParams) => Promise<PrepareWebCompileResult>;
|
|
484
|
+
//#endregion
|
|
485
|
+
//#region src/node/utils/logger.d.ts
|
|
486
|
+
declare const LoggerSystem: () => {
|
|
487
|
+
done: ({
|
|
488
|
+
text,
|
|
489
|
+
onlyText
|
|
490
|
+
}: {
|
|
491
|
+
text: string;
|
|
492
|
+
onlyText?: boolean;
|
|
493
|
+
}) => string | undefined;
|
|
494
|
+
error: ({
|
|
495
|
+
text,
|
|
496
|
+
onlyText
|
|
497
|
+
}: {
|
|
498
|
+
text: string;
|
|
499
|
+
onlyText?: boolean;
|
|
500
|
+
}) => string | undefined;
|
|
501
|
+
okay: ({
|
|
502
|
+
text,
|
|
503
|
+
onlyText
|
|
504
|
+
}: {
|
|
505
|
+
text: string;
|
|
506
|
+
onlyText?: boolean;
|
|
507
|
+
}) => string | undefined;
|
|
508
|
+
warning: ({
|
|
509
|
+
text,
|
|
510
|
+
onlyText
|
|
511
|
+
}: {
|
|
512
|
+
text: string;
|
|
513
|
+
onlyText?: boolean;
|
|
514
|
+
}) => string | undefined;
|
|
515
|
+
info: ({
|
|
516
|
+
text,
|
|
517
|
+
onlyText
|
|
518
|
+
}: {
|
|
519
|
+
text: string;
|
|
520
|
+
onlyText?: boolean;
|
|
521
|
+
}) => string | undefined;
|
|
522
|
+
emitEvent: (event: string) => void;
|
|
523
|
+
clearEventArray: () => void;
|
|
524
|
+
eventArray: string[];
|
|
525
|
+
};
|
|
526
|
+
//#endregion
|
|
527
|
+
//#region src/node/utils/rspack-runner.d.ts
|
|
528
|
+
type BuildStatus = {
|
|
529
|
+
success: boolean;
|
|
530
|
+
port?: number;
|
|
531
|
+
message?: string;
|
|
532
|
+
};
|
|
533
|
+
type WatchRspackBuildOptions = WatchOptions & {
|
|
534
|
+
onBuildStatus?: (status: BuildStatus) => void;
|
|
535
|
+
};
|
|
536
|
+
declare const runRspackBuild: (config: Configuration | Configuration[], options?: WatchRspackBuildOptions) => Promise<string | undefined>;
|
|
537
|
+
declare const watchRspackBuild: (config: Configuration | Configuration[], options?: WatchRspackBuildOptions) => Promise<string | undefined>;
|
|
538
|
+
//#endregion
|
|
539
|
+
//#region src/node/utils/const.d.ts
|
|
540
|
+
declare const extensions: string[];
|
|
541
|
+
/**
|
|
542
|
+
* 基于cli的绝对定位
|
|
543
|
+
* @param ...paths 子路径
|
|
544
|
+
*/
|
|
545
|
+
declare const resolveCLI: (...paths: string[]) => string;
|
|
546
|
+
//#endregion
|
|
547
|
+
export { BaseCompileService, Bundler, Command, type CompileOptions, type CompileServeParame, ConfigEnvPre, CreateLoader, CreatePlugins, ElectronConfig, LoggerSystem, ModuleFederationOptions, type OptionalViteAdapter, type PackageJson, UserConfig, UserConfigFn, UserConfigWebExport, WebCompileService, defineConfig, extensions, loadOptionalViteAdapter, prepareWebCompile, resolveCLI, runRspackBuild, watchRspackBuild };
|
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import e from"node:module";import{Option as t,program as n}from"commander";import r,{join as i}from"path";import a from"node:fs";import o from"node:fs/promises";import s from"fs-extra";import{config as c}from"dotenv";import{LoggerQueue as l,LoggerSystem as u,transformCode as d}from"@ikaros-cli/infra-contrlibs";import f,{dirname as ee,extname as p,join as m,resolve as h}from"node:path";import g,{pathToFileURL as _}from"node:url";import{parse as te}from"yaml";import{isArray as v,isEmpty as y,isFunction as b,isObject as x,isString as S}from"radashi";import{detect as ne}from"detect-port";import C from"chalk";import{rspack as w}from"@rspack/core";import{RsdoctorRspackPlugin as re}from"@rsdoctor/rspack-plugin";import ie from"compression-webpack-plugin";import ae from"eslint-webpack-plugin";import oe from"stylelint-webpack-plugin";import{RspackDevServer as se}from"@rspack/dev-server";import T from"fs/promises";import{z as E}from"zod";import ce from"ora";import le from"node:os";import D from"pretty-bytes";import ue from"easy-table";import de from"cli-cursor";import O from"node:process";import{ModuleFederationPlugin as k}from"@module-federation/enhanced/rspack";var fe=`@ikaros-cli/ikaros`,A=`1.4.0`;const j=e=>e?i(M,`env`,`.env.${e}`):i(M,`env`,`.env`),pe=async e=>{let{emitEvent:t}=l(),{warning:n}=new u,r=await s.pathExists(i(M,`env`));if(!r)return t(n({text:`env folder not found`,onlyText:!0})),!1;if(e){let r=await s.pathExists(j(e));if(!r)return t(n({text:`.env.${e} file not found`,onlyText:!0})),!1}else{let e=await s.pathExists(j());return e?!0:(t(n({text:`.env file not found`,onlyText:!0})),!1)}return!0},M=process.cwd(),N=async e=>{let t=await pe(e);return t?e?c({quiet:!1,path:j(e)}).parsed??{}:c({quiet:!1,path:j()}).parsed??{}:{}};async function me(e,t){let{code:n}=await d(e,{lang:t?`ts`:`js`});return{code:n}}async function P(e,t){let n=`${e}.timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`,r=`${n}.mjs`,i=`${_(n)}.mjs`;await o.writeFile(r,t);try{let e=await import(i);return e.default}finally{await o.unlink(r)}}async function F(e,t){let{code:n}=await me(e,t);return P(e,n)}const I=new Map;I.set(`.mjs`,async e=>{let t=_(e),n=await import(t.href);return n.default}),I.set(`.ts`,async e=>await F(e,!0)),I.set(`.json`,async e=>await s.readJson(e)),I.set(`.yaml`,async e=>{let t=await o.readFile(e,`utf8`);return te(t)});async function L({configFile:e}){let t,n=process.cwd(),r=`ikaros.config`,i=[`ts`,`mjs`,`json`,`yaml`].map(e=>`${m(n,r)}.${e}`),a=await Promise.all(i.map(e=>s.pathExists(e))),o=a.findIndex(Boolean);if(!(o<0)){if(t=p(i[o]),n=h(n,`${r}${t}`),e&&(n=ee(e),t=p(e)),!I.has(t))throw Error(`No configuration file ! `);return{filePath:n,config:await I.get(t)(n)}}}let R=function(e){return e.SERVER=`server`,e.BUILD=`build`,e}({});var z=class{command;context;options;contextRequire;_env;configFile;logger=new u;version=A;set env(e){this._env=e}get env(){return this._env}_contextPkg;set contextPkg(e){this._contextPkg=e}get contextPkg(){return this._contextPkg}constructor(t){let{command:n,options:r,configFile:a}=t;this.command=n,this.options=r,this.configFile=a,this.context=i(process.cwd(),`./`),this.contextRequire=e.createRequire(this.context)}async initialize(){await this.initContextPkg(),await this.initEnv()}resolveContext(...e){return i(this.context,...e)}async initContextPkg(){let e=this.resolveContext(`package.json`);try{await o.access(e,a.constants.F_OK)}catch{return}let t=await o.readFile(e,{encoding:`utf8`});this.contextPkg=JSON.parse(t)}async initEnv(){let{platform:e,mode:t}=this.options,n={PLATFORM:e,MODE:t},r=await N(t),i=await N(`local`);this.env={...n,...r,...i}}resolveContextModule(e){try{return this.contextRequire.resolve(e)}catch{return}}loadContextModule(e){return this.contextRequire(e)}async getUserConfig(){let{configFile:e}=this,t=await L({configFile:e}),n;if(t){if(b(t.config)){let e={PLATFORM:this.options.platform},r={mode:this.options.mode??``,env:Object.assign(e,this.env),command:this.command};n=await t.config(r)}return x(t.config)&&(n=t.config),n}}watchDogServer(){}};const B=i(process.cwd(),`./`),he=[`...`,`.css`,`.less`,`.sass`,`.scss`,`.mjs`,`.jsx`,`.ts`,`.tsx`,`.node`,`.vue`];i(B,`tsconfig.json`);const V=g.fileURLToPath(new g.URL(`../`,import.meta.url)),ge=e.createRequire(V),_e=(...e)=>i(V,...e),H=(e,t)=>({loader:e.includes(`builtin`)?e:ge.resolve(e),parallel:!e.includes(`sass`),options:t}),ve=(e,t)=>{let{lightningcss:n,sourceMap:r}=t??{},i=H(`builtin:lightningcss-loader`,{...n}),a=(e,n)=>{let a=[i],o=t&&t[`${e}`];return e&&e!==`css`&&a.push(H(`${e}-loader`,Object.assign(o??{},n,{sourceMap:r}))),a};return{less:a(`less`),sass:a(`sass`,{sassOptions:{indentedSyntax:!0,api:`modern-compiler`}}),scss:a(`sass`,{sassOptions:{api:`modern-compiler`}}),stylus:a(`stylus`),styl:a(`stylus`),css:a(`css`)}},ye=(e,t)=>{let n=ve(e,t);return Object.entries(n).map(([e,t])=>({test:RegExp(`\\.${e}$`),use:t,type:`css/auto`}))},U=(e,t)=>{for(let n in t)e[n]=x(t[n])&&n in e?U(e[n],t[n]):t[n];return e};async function W(e){try{let t=i(process.cwd(),`node_modules`,e);return await T.access(t,T.constants.F_OK),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}E.object({target:E.enum([`pc`,`mobile`]).optional().default(`pc`),pages:E.custom().optional(),enablePages:E.union([E.array(E.string())]).optional(),moduleFederation:E.union([E.custom(),E.array(E.custom())]).optional(),plugins:E.union([E.custom(),E.array(E.custom())]).optional(),loaders:E.array(E.custom()).optional(),experiments:E.custom().optional(),cdnOptions:E.custom().optional(),server:E.object({port:E.number().int().min(1024).max(65535).optional(),proxy:E.custom().optional(),https:E.union([E.boolean(),E.record(E.string(),E.any())]).optional().default(!1)}).optional(),css:E.object({lightningcssOptions:E.record(E.string(),E.any()).optional(),sourceMap:E.boolean().optional(),lessOptions:E.record(E.string(),E.any()).optional(),sassOptions:E.record(E.string(),E.any()).optional(),stylusOptions:E.record(E.string(),E.any()).optional()}).optional(),build:E.object({base:E.string().optional().default(`/`),assetsDir:E.string().optional(),gzip:E.boolean().optional().default(!1),sourceMap:E.boolean().optional().default(!1),outDirName:E.string().optional().default(`dist`),outReport:E.boolean().optional().default(!1),cache:E.boolean().optional().default(!1),dependencyCycleCheck:E.boolean().optional().default(!1)}).optional(),resolve:E.object({alias:E.record(E.string(),E.string()).optional(),extensions:E.array(E.string()).optional()}).optional()});var G=class{list=[];env=`development`;mode=``;isDev=!0;constructor({env:e=`development`,mode:t=``}){this.env=e,this.mode=t,this.isDev=e===`development`}add(e){return v(e)?this.list=this.list.concat(e):e&&this.list.push(e),this}end(){return this.list}},be=class extends G{constructor({env:e=`development`,mode:t=``}){super({env:e,mode:t})}defaultScriptLoader=e=>({test:/\.m?[j]s$/,loader:`builtin:swc-loader`,options:{isModule:`unknown`,rspackExperiments:e},type:`javascript/auto`});defaultResourceLoader=[{test:/\.(png|jpe?g|gif|svg|ico)(\?.*)?$/,type:`asset/resource`,generator:{filename:this.isDev?`[id][ext]`:`assets/img/[contenthash][ext]`}},{test:/\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,type:`asset/resource`,generator:{filename:this.isDev?`[id][ext]`:`assets/media/[contenthash][ext]`}},{test:/\.(woff2?|eot|ttf|otf)(\?.*)?$/,type:`asset/resource`,generator:{filename:this.isDev?`[id][ext]`:`assets/fonts/[contenthash][ext]`}}];useDefaultCssLoader(e){let t=ye(this.env,e);return t.forEach(e=>this.add(e)),this}useDefaultScriptLoader(e){return this.add(this.defaultScriptLoader(e)),this}useDefaultResourceLoader(){return this.defaultResourceLoader.forEach(e=>this.add(e)),this}},xe=class extends G{constructor({env:e=`development`,mode:t=``}){super({env:e,mode:t})}useDefaultEnvPlugin(e){let{frameworkEnv:t={},extEnv:n={},env:r={}}=e??{};return this.add(Ce({frameworkEnv:t,extEnv:n,env:r})),this}useCopyPlugin(){return this.env===`production`&&this.add(new w.CopyRspackPlugin({patterns:[{context:i(B,`public`),from:`./`,noErrorOnMissing:!0,globOptions:{ignore:[`**/index.html`,`.*`]}}]})),this}useHtmlPlugin(e){return this.add(new w.HtmlRspackPlugin({template:e??i(B,`index.html`)})),this}},Se=class{pages;enablePages;logger=l();loggerSystem=new u;constructor({pages:e,enablePages:t}){this.pages=e,this.enablePages=t,this.getEnablePages()}create(){let e={},t=[];return Object.keys(this.pages).forEach(n=>{e[n]={import:this.pages[n].entry,library:this.pages[n].library},t.push(new w.HtmlRspackPlugin({template:this.pages[n].html,filename:`${n}.html`,chunks:[n],scriptLoading:`blocking`,...this.pages[n].options}))}),{entry:e,plugins:t}}getEnablePages(){if(!y(this.pages)&&v(this.enablePages)){let e={},t=[];if(this.enablePages.forEach(n=>{this.pages[n]?e[n]=this.pages[n]:t.push(n)}),t.length&&this.logger.emitEvent(this.loggerSystem.warning({text:`当前设置页面${t.join()}不存在`,onlyText:!0})),y(e))return;this.pages=e}}};const Ce=({frameworkEnv:e={},extEnv:t={},env:n={}})=>{let r=Object.assign({},U(t,n)),i=Object.fromEntries(Object.entries(r).map(([e,t])=>[`import.meta.env.${e}`,JSON.stringify(t)])),a=Object.fromEntries(Object.entries({...i,...e,"import.meta.env":JSON.stringify({})}).map(([e,t])=>[e,t]));return new w.DefinePlugin(a)},K={name:fe,version:A},q=`@rspack/ikaros-stats-plugin`,J=C.hex(`#222222`);var we=class{compiler;ora;config;startCompileHrtime=void 0;isDev;lastProgressText;constructor(e){this.config=e,this.ora=ce({color:`cyan`,prefixText:``,hideCursor:!1})}apply(e){this.compiler=e,this.isDev=e.options.mode===`development`,new w.ProgressPlugin(this.progressHandler.bind(this)).apply(e),de.hide(),this.isDev?this.initDevHook():this.initProdHook()}progressHandler(e,t,...n){let r=`${(e*100).toFixed(2)}%`;r+=` ${t} `,r+=C.gray(n?.join(` `)),this.lastProgressText!==r&&(this.lastProgressText=r,this.isDev?this.ora.text=`${r}\n`:console.log(r))}updateStartCompileTime(){this.startCompileHrtime=O.hrtime()}getCurrentEndCompileTime(){let e=O.hrtime(this.startCompileHrtime);return(e[0]*1e9+e[1])/1e6}getError(e){let{errors:t,errorsCount:n=0}=e;if(!(!t||n===0))return t.map(e=>`${J.bgRed(` ERROR `)} ${e.message.trim()}`).join(`
|
|
2
|
-
|
|
3
|
-
`)}
|
|
4
|
-
|
|
5
|
-
`)
|
|
6
|
-
`)),console.log()),c>0)console.log(this.getError(s)),console.log();else{u>0&&(console.log(this.getWarn(s)),console.log());let{name:e,version:t}=K,o=`${i(`${e} v${t}`)} entry address:\n\n`;for(let e of n)o+=r(` ${e}\n`);console.log(a(o))}console.log(this.getEndTips(s,this.getCurrentEndCompileTime())),console.log()}})}initProdHook(){let{compiler:e}=this,t,n=!1;e.hooks.environment.intercept({name:q,call:()=>{console.log(C.gray(`start build...`)),this.updateStartCompileTime()}}),e.hooks.failed.intercept({name:q,call:()=>{n=!0,console.log(C.red(`build failed`)),console.clear()}}),e.hooks.done.intercept({name:q,call:e=>{t=e.toJson({preset:`normal`,colors:!0,assetsSort:`size`}),this.handleProOutput(t,n)}})}handleProOutput(e,t){if(t)return;console.clear();let{errorsCount:n=0,warningsCount:r=0}=e;console.log(),n>0?(console.log(this.getError(e)),console.log()):(r>0&&(console.log(this.getWarn(e)),console.log()),e&&console.log(this.getTableInfo(e)),console.log()),console.log(this.getEndTips(e,this.getCurrentEndCompileTime()))}};const Y=`@rspack/ikaros-cdn-plugin`,Te=`https://unpkg.com/:name@:version/:path`,Ee=`:name/:path`,X=/:([a-z]+)/gi;var De=class{compiler;options;isDev=!1;logger=l();loggerSystem=new u;constructor(e){this.options={prodUrl:Te,devUrl:Ee,crossOrigin:!1,sri:!1,useLocal:!1,...e}}apply(e){this.compiler=e,this.isDev=e.options.mode===`development`,!this.options.useLocal&&this.handleExternals(),e.hooks.compilation.tap(Y,e=>{let t=w.HtmlRspackPlugin.getCompilationHooks(e);t.beforeAssetTagGeneration.tapAsync(Y,(e,t)=>{if(e.plugin.options.meta&&!y(e.plugin.options.meta.assetsLoadFilePath)&&!this.isDev)return e.assets.js=this.removeChunkJs(e),t(null,e);t(null,e)}),t.alterAssetTags.tapAsync(Y,(e,t)=>{try{!this.options.useLocal&&this.injectResources(e),t(null,e)}catch(e){t(e)}}),t.beforeEmit.tapAsync(Y,async(e,t)=>{if(e.plugin.options.meta&&!y(e.plugin.options.meta.assetsLoadFilePath)&&!this.isDev){let n=e.plugin.options.meta.assetsLoadFilePath??``;return e.html=this.removeLink(e),e.html=await this.inlineJs(n,e),t(null,e)}t(null,e)})})}handleExternals(){let e=this.compiler.options.externals||{};this.options.modules.filter(e=>!e.cssOnly).forEach(t=>{e[t.name]=t.var||t.name}),this.compiler.options.externals=e}injectResources(e){let t=this.options.modules,n=[];t.forEach(e=>{let t=this.getStyles(e);t.forEach(e=>{n.push({tagName:`link`,voidTag:!0,attributes:{rel:`stylesheet`,href:e,...this.options.crossOrigin&&{crossorigin:this.options.crossOrigin}}})})}),t.filter(e=>!e.cssOnly).forEach(e=>{let t=this.getScripts(e);t.forEach(e=>{n.push({tagName:`script`,voidTag:!0,attributes:{src:e,...this.options.crossOrigin&&{crossorigin:this.options.crossOrigin}}})})}),e.assetTags&&(e.assetTags.styles.unshift(...n.filter(e=>e.tagName===`link`)),e.assetTags.scripts.unshift(...n.filter(e=>e.tagName===`script`)))}getStyles(e){let t=[...e.styles||[]];return e.style&&t.unshift(e.style),t.map(t=>this.generateUrl(e,t))}getScripts(e){let t=[...e.paths||[]];return e.path&&t.unshift(e.path),t.map(t=>this.generateUrl(e,t))}joinUrl(e,t){return e=e.replace(/\/+$/,``),t=t.replace(/^\/+/,``),`${e}/${t}`}generateUrl(e,t){let n=this.isDev?e.devUrl||this.options.devUrl:e.prodUrl||this.options.prodUrl;return n.match(X)?n.replace(X,(n,r)=>{switch(r){case`name`:return e.name;case`version`:return e.version||this.getModuleVersion(e.name);case`path`:return t;default:return n}}):this.joinUrl(n,t)}getModuleVersion(t){try{return e.createRequire(r.join(process.cwd(),`node_modules`))(r.join(t,`package.json`)).version}catch{return this.logger.emitEvent(this.loggerSystem.warning({text:`[${Y}] 无法获取模块 "${t}" 的版本信息,回退到 "latest"`,onlyText:!0})),`latest`}}removeChunkJs(e){let t=this.options.modules,n=t.filter(e=>!e.cssOnly).flatMap(e=>this.getScripts(e));return!e?.assets||!e.assets.js?[]:e.assets.js.filter(e=>n.includes(e))}removeLink(e){return e.html.replace(/<link(.*?)>/g,``)}async inlineJs(e,t){if(!a.existsSync(e))return t.html.toString();let{code:n}=await this.compiler.rspack.experiments.swc.minify(a.readFileSync(e,`utf-8`)||``,{ecma:5,compress:{drop_console:!0,drop_debugger:!0}}),r=`<script>${n}<\/script>`,i=t.html.toString();return i.replace(RegExp(`</body>`,`g`),`</body>`+r)}},Oe=class{devServer;resolvedContext;browserslist;base;userConfig;pages;port;logger=new u;isVue=!1;isReact=!1;constructor(e){this.resolvedContext=e,this.browserslist=e.browserslist??`defaults`,this.base=e.base,this.userConfig=e.userConfig,this.pages=e.pages,this.port=e.port}joinAssetsDir(...e){let t=this.userConfig?.build?.assetsDir??``;return m(t,...e).replaceAll(`\\`,`/`)}getOutDirPath(){let e=this.userConfig?.build?.outDirName;return S(e)?this.resolvedContext.resolveContext(e):this.resolvedContext.resolveContext(`dist`)}async initOtherConfig(){try{let[e,t]=await Promise.all([W(`react`),W(`vue`)]);this.isVue=t,this.isReact=e}catch{}}},Z=class extends Oe{createSourceMapPlugin(){let e=this.resolvedContext.command===R.SERVER;if(e)return new w.EvalSourceMapDevToolPlugin({columns:!1,module:!0});if(this.userConfig?.build?.sourceMap??!1)return new w.SourceMapDevToolPlugin({test:[/.js/,/.mjs/],filename:`[file].map[query]`})}createEslintPlugin(){let e=this.userConfig?.eslint||!1,t=this.userConfig?.stylelint||!1,n=this.resolvedContext.command===R.SERVER,r=[];return e&&r.push(new ae({context:this.resolvedContext.context,eslintPath:this.resolvedContext.resolveContext(`node_modules/eslint`),extensions:[`js`,`vue`,`ts`,`tsx`],fix:e===`fix`,cache:!0,threads:!0,lintDirtyModulesOnly:n,failOnError:!1,failOnWarning:!1})),t&&r.push(new oe({context:this.resolvedContext.context,extensions:[`css`,`scss`,`less`,`vue`],fix:t===`fix`,cache:!0,threads:!0,lintDirtyModulesOnly:n,failOnError:!1,failOnWarning:!1})),r}createDoctorPlugin(){if(this.resolvedContext.command!==R.SERVER&&this.userConfig?.build?.outReport)return new re}createGzipPlugin(){if(this.resolvedContext.command!==R.SERVER&&this.userConfig?.build?.gzip)return new ie}createOptimization(){return this.resolvedContext.command===R.SERVER?{minimize:!1,removeEmptyChunks:!1,splitChunks:!1}:{minimize:!0,splitChunks:{chunks:`async`,minSize:2e4,minChunks:2,cacheGroups:{defaultVendors:{name:`chunk-vendors`,test:/[\\/]node_modules[\\/]/,priority:-10,reuseExistingChunk:!0,chunks:`initial`},default:{name:`chunk-common`,minChunks:2,priority:-20,reuseExistingChunk:!0,chunks:`initial`}}}}}createCacheConfig(){if(this.resolvedContext.command!==R.SERVER&&this.userConfig?.build?.cache)return{cache:!0,experiments:{cache:{type:`persistent`}}}}createCdnPlugin(){let{cdnOptions:e}=this.userConfig??{};if(!(!e||y(e.modules)))return new De(e)}createVueOrReactConfig(){return this.isVue?{noParse:/^(vue|vue-router|vuex|vuex-router-sync)$/,env:{__VUE_OPTIONS_API__:!0,__VUE_PROD_DEVTOOLS__:!1,__VUE_PROD_HYDRATION_MISMATCH_DETAILS__:!1}}:this.isReact?{noParse:e=>/(react|react-dom|react-is)\.production\.min\.js$/.test(e),env:{REACT_APP_ENABLE_DEVTOOLS:!1}}:{env:void 0,noParse:void 0}}createModuleFederationPlugin(){let e=this.userConfig?.moduleFederation;if(e)return v(e)?e.map(e=>new k(e)):new k(e)}createLimitChunksPlugin(){if(this.resolvedContext.command===R.SERVER||!this.userConfig?.build?.maxChunks)return;let e=this.userConfig?.build?.maxChunks??1;return(typeof e==`boolean`&&!e||e<1)&&(e=1),new w.optimize.LimitChunkCountPlugin({maxChunks:e})}createDependencyCyclePlugin(){if(this.resolvedContext.command!==R.SERVER&&this.userConfig?.build?.dependencyCycleCheck)return new w.CircularDependencyRspackPlugin({exclude:/node_modules/,failOnError:!1})}async createRspackConfig(){let e=this.resolvedContext.command===R.SERVER,t=e?`development`:`production`,n=new be({env:t,mode:this.resolvedContext.options.mode}),r=new xe({env:t,mode:this.resolvedContext.options.mode}),i=new Se({pages:this.pages,enablePages:this.userConfig?.enablePages}),{entry:a,plugins:o}=i.create(),{env:s,noParse:c}=this.createVueOrReactConfig(),l=n.useDefaultResourceLoader().useDefaultScriptLoader(this.userConfig?.experiments).useDefaultCssLoader(this.userConfig?.css).add(this.userConfig?.loaders).end(),u=r.useDefaultEnvPlugin({extEnv:{CLI_VER:this.resolvedContext.version,frameworkEnv:s,...this.userConfig?.define},frameworkEnv:{__VUE_OPTIONS_API__:!0,__VUE_PROD_DEVTOOLS__:!1,__VUE_PROD_HYDRATION_MISMATCH_DETAILS__:!1},env:this.resolvedContext.env}).useCopyPlugin().add(o).add(new we({pages:this.pages,base:this.base,gzip:this.userConfig?.build?.gzip??!1})).add(this.createSourceMapPlugin()).add(this.createDoctorPlugin()).add(this.createGzipPlugin()).add(this.createCdnPlugin()).add(this.createModuleFederationPlugin()).add(this.createEslintPlugin()).add(this.createLimitChunksPlugin()).add(this.createDependencyCyclePlugin()).add(this.userConfig?.plugins).end();return{mode:t,target:[`web`,`es5`,`browserslist:${this.browserslist}`],context:this.resolvedContext.context,entry:a,resolve:{alias:{"@":this.resolvedContext.resolveContext(`src`),...this.userConfig?.resolve?.alias},extensions:this.userConfig?.resolve?.extensions||he,modules:[`node_modules`,this.resolvedContext.resolveContext(`node_modules`),_e(`node_modules`)]},output:{clean:!0,path:this.getOutDirPath(),publicPath:this.base,filename:e?`[id].js`:this.joinAssetsDir(`assets/js/[name].[contenthash].js`),chunkLoadingGlobal:`${this.resolvedContext.contextPkg?.name||`ikaros`}_chunk`,pathinfo:!1},optimization:this.createOptimization(),stats:`none`,watchOptions:{aggregateTimeout:500,ignored:/node_modules/},module:{rules:l,noParse:c},plugins:u,devServer:{hot:!0,port:this.port,server:(()=>{let e=this.userConfig?.server?.https;return e?e===!0?`https`:{type:`https`,options:e}:`http`})(),allowedHosts:`all`,proxy:this.userConfig?.server?.proxy,historyApiFallback:{rewrites:[{from:RegExp(`^${this.base}`),to:m(this.base,`index.html`)}]},headers:{"Access-Control-Allow-Origin":`*`},static:{directory:this.resolvedContext.resolveContext(`public`),publicPath:this.base},client:{logging:`none`,overlay:{errors:!0,warnings:!1,runtimeErrors:!1},webSocketURL:`auto://0.0.0.0:${this.port}/ws`}},experiments:{css:!0,lazyCompilation:!0,parallelLoader:!0,incremental:!0},...this.createCacheConfig()}}async createRspackBuilder({isLive:e,config:t}){return new Promise((n,r)=>{let i=w(t);if(e){this.devServer=new se(t.devServer,i),this.devServer.startCallback(e=>{if(e)return r(e);n(void 0)});return}i.run((e,t)=>{i.close(r=>((e||r)&&process.exit(2),t?.hasErrors()&&(this.logger.error({text:`Build failed with errors.`}),process.exit(2)),n(t?.toString({timings:!0,colors:!0}))))})})}async restartServer(){if(this.devServer){await this.devServer.stop();let e=await this.createRspackConfig();await this.createRspackBuilder({isLive:!0,config:e})}}async serve(){let e=await this.createRspackConfig();await this.createRspackBuilder({isLive:!0,config:e})}async build(){let e=await this.createRspackConfig();await this.createRspackBuilder({config:e})}};const ke={rspack:Z};var Ae=class extends z{userConfig;base;browserslist;isVue=!1;isReact=!1;target;platform;engine=`rspack`;port;pages;async initUserConfig(){let e=this.command===R.SERVER,t=await this.getUserConfig();if(this.userConfig=t,this.base=t?.build?.base??`/`,e&&S(this.base)&&/^https?:/.test(this.base)){let e=C.cyan(`build.base`);throw this.logger.error({text:` 本地开发时 ${e} 不应该为外部 Host!`}),Error(`错误的配置: ${e} 不应为外部 Host`)}this.target=t?.target??`pc`,this.platform=t?.platform??`web`,this.pages=t?.pages??{index:{html:this.resolveContext(`index.html`),entry:this.resolveContext(`src/index`)}},this.port=await ne(t?.server?.port||`8080`),this.engine=t?.engine??`rspack`}async initBrowserslist(){let e=this.target===`mobile`,t=[`defaults`];e?t.push(`IOS >= 10`,`Chrome >= 51`):t.push(`>=0.1%`,`Chrome >= 56`,`Safari >= 10`,`last 2 versions`,`not dead`),this.browserslist=t.join(`,`)}async initOtherConfig(){try{let[e,t]=await Promise.all([W(`react`),W(`vue`)]);this.isVue=t,this.isReact=e}catch{}}async initPreConfig(){return await this.initialize(),await Promise.all([this.initUserConfig(),this.initOtherConfig(),this.initBrowserslist()]),{userConfig:this.userConfig,command:this.command,options:this.options,context:this.context,contextPkg:this.contextPkg,version:this.version,env:this.env,base:this.base,port:this.port,pages:this.pages,browserslist:this.browserslist,resolveContext:this.resolveContext.bind(this)}}async createEngine(){let e=await this.initPreConfig();if(!this.userConfig)throw this.logger.error({text:`用户配置未加载,请检查配置文件。`}),Error(`userConfig is not loaded`);let t=ke[this.engine];if(!t)throw Error(`Unsupported build engine: ${this.engine}`);return new t(e)}async dev(){let e=await this.createEngine();e.serve()}async build(){let e=await this.createEngine();e.build()}};const Q={WEB:`web`},je=[new t(`-m, --mode <name>`,`Environment variable`),new t(`-p, --platform <type>`,`build platform type`).default(Q.WEB).choices(Object.values(Q))],$=async e=>{let{error:t}=new u,n=null;try{switch(e.options.platform){case Q.WEB:n=new Ae(e);break;default:{let n=Object.values(Q).join(`,`);throw t({text:`No corresponding compilation service was found, platform: ${n}`}),Error(`No corresponding compilation service was found, platform: ${e.options.platform}`)}}}catch(e){throw Error(e instanceof Error?e.message:String(e))}return n},Me=e=>{let t=e.command(R.SERVER,{isDefault:!0}).description(`Start local develop serve`).action(async e=>{let t=await $({command:R.SERVER,options:e});t.dev()}),n=e.command(R.BUILD).description(`Start build`).action(async e=>{let t=await $({command:R.BUILD,options:e});t.build()});for(let e of je)t.addOption(e),n.addOption(e)},Ne=e=>e,{error:Pe}=new u,Fe=Number(process.versions.node.split(`.`)[0]);if(Fe<20)throw Pe({text:`The Node.js version is greater than v20!`}),Error(`The Node.js version is greater than v20!`);n.version(A,`-v, --version`),Me(n),n.parse();export{Ne as defineConfig};
|
|
1
|
+
import{createRequire as e}from"node:module";import{Option as t,program as n}from"commander";import{dirname as r,extname as i,join as a,resolve as o}from"node:path";import s,{pathToFileURL as c}from"node:url";import l from"node:fs";import u,{readFile as d}from"node:fs/promises";import{isFunction as f,isString as p}from"es-toolkit";import{isArray as m,isEmpty as h,isObject as g}from"es-toolkit/compat";import _ from"fs/promises";import{z as v}from"zod/v4";import y,{join as b}from"path";import x from"fs-extra";import{config as S}from"dotenv";import C from"chalk";import{parse as w}from"yaml";import{transform as T}from"oxc-transform";import{rspack as E}from"@rspack/core";import{RspackDevServer as ee}from"@rspack/dev-server";import{RsdoctorRspackPlugin as te}from"@rsdoctor/rspack-plugin";import ne from"compression-webpack-plugin";import{ModuleFederationPlugin as D}from"@module-federation/enhanced/rspack";import{detect as re}from"detect-port";var ie=`2.1.0`;const O=(e,t)=>{let n=e,r=t;for(let e of Object.keys(r)){let t=r[e],i=n[e];g(t)&&g(i)?n[e]=O(i,t):n[e]=t}return e};async function k(e){try{let t=b(process.cwd(),`node_modules`,e);return await _.access(t,_.constants.F_OK),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}const ae={target:v.enum([`pc`,`mobile`]).optional().default(`pc`),pages:v.custom().optional(),enablePages:v.union([v.array(v.string()),v.literal(!1)]).optional(),define:v.custom().optional(),build:v.object({base:v.string().optional().default(`/`),assetsDir:v.string().optional(),sourceMap:v.boolean().optional().default(!1),outDirName:v.string().optional().default(`dist`)}).optional(),resolve:v.object({alias:v.record(v.string(),v.string()).optional(),extensions:v.array(v.string()).optional()}).optional(),server:v.object({port:v.number().int().min(1024).max(65535).optional()}).optional(),electron:v.unknown().optional()},oe=v.object({bundler:v.custom().optional().default(`rspack`).refine(e=>e===`rspack`,{message:`bundler must be 'rspack' for rspack config`}),...ae,moduleFederation:v.union([v.custom(),v.array(v.custom())]).optional(),plugins:v.union([v.custom(),v.array(v.custom())]).optional(),loaders:v.array(v.custom()).optional(),experiments:v.custom().optional(),cdnOptions:v.custom().optional(),server:v.object({port:v.number().int().min(1024).max(65535).optional(),proxy:v.custom().optional(),https:v.union([v.boolean(),v.record(v.string(),v.unknown())]).optional().default(!1)}).optional(),css:v.object({lightningcssOptions:v.record(v.string(),v.unknown()).optional(),sourceMap:v.boolean().optional(),lessOptions:v.record(v.string(),v.unknown()).optional(),sassOptions:v.record(v.string(),v.unknown()).optional(),stylusOptions:v.record(v.string(),v.unknown()).optional()}).optional(),build:v.object({base:v.string().optional().default(`/`),assetsDir:v.string().optional(),gzip:v.boolean().optional().default(!1),sourceMap:v.boolean().optional().default(!1),outDirName:v.string().optional().default(`dist`),outReport:v.boolean().optional().default(!1),cache:v.boolean().optional().default(!1),dependencyCycleCheck:v.boolean().optional().default(!1)}).optional()}),se=v.object({bundler:v.literal(`vite`),...ae,server:v.object({port:v.number().int().min(1024).max(65535).optional(),proxy:v.record(v.string(),v.unknown()).optional(),https:v.union([v.boolean(),v.record(v.string(),v.unknown())]).optional()}).optional(),vite:v.object({plugins:v.unknown().optional()}).strict().optional()}).passthrough().superRefine((e,t)=>{for(let n of[`plugins`,`loaders`,`experiments`,`cdnOptions`,`moduleFederation`,`css`]){let r=e;n in r&&r[n]!==void 0&&t.addIssue({code:v.ZodIssueCode.custom,path:[n],message:`bundler='vite' 时不支持 ${String(n)},请使用 vite.plugins 或 Vite 原生配置能力`})}}),A=v.union([se,oe]),j=[],M=()=>{let e=(e,t)=>({DONE:C.bgGreen.white,ERROR:C.bgRed.white,OKAY:C.bgBlue.white,WARNING:C.bgYellow.white,INFO:C.bgCyan.white})[e](` ${e} `)+` ${t}`;return{done:({text:t,onlyText:n})=>{if(n)return e(`DONE`,t);console.log(e(`DONE`,t))},error:({text:t,onlyText:n})=>{if(n)return e(`ERROR`,t);console.error(e(`ERROR`,t))},okay:({text:t,onlyText:n})=>{if(n)return e(`OKAY`,t);console.log(e(`OKAY`,t))},warning:({text:t,onlyText:n})=>{if(n)return e(`WARNING`,t);console.warn(e(`WARNING`,t))},info:({text:t,onlyText:n})=>{if(n)return e(`INFO`,t);console.info(e(`INFO`,t))},emitEvent:e=>{let t=new Date().toLocaleTimeString(`en-US`,{hour12:!1}).split(` `)[0];j.push(`[${t}] ${e}`)},clearEventArray:()=>{j.length=0},eventArray:j}},N=e=>e?b(P,`env`,`.env.${e}`):b(P,`env`,`.env`),ce=async e=>{let{warning:t,emitEvent:n}=M();if(!await x.pathExists(b(P,`env`)))return n(t({text:`env folder not found`,onlyText:!0})),!1;if(e){if(!await x.pathExists(N(e)))return n(t({text:`.env.${e} file not found`,onlyText:!0})),!1}else return await x.pathExists(N())?!0:(n(t({text:`.env file not found`,onlyText:!0})),!1);return!0},P=process.cwd(),le=async e=>await ce(e)?e?S({path:N(e),quiet:!0}).parsed??{}:S({path:N(),quiet:!0}).parsed??{}:{};async function ue(e,t){let{code:n,errors:r}=await T(e,await d(e,`utf-8`),{lang:t?`ts`:`js`});if(r.length>0)throw Error(`Transformation failed: `+r.map(e=>e.message).join(`, `));return{code:n}}async function de(e,t){let n=`${e}.timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`,r=`${n}.mjs`,i=`${c(n)}.mjs`;await u.writeFile(r,t);try{return(await import(i)).default}finally{await u.unlink(r)}}async function fe(e,t=!1){let{code:n}=await ue(e,t);return de(e,n)}const F=new Map;F.set(`.mjs`,async e=>(await import(c(e).href)).default),F.set(`.ts`,async e=>await fe(e,!0)),F.set(`.json`,async e=>await x.readJson(e)),F.set(`.yaml`,async e=>w(await u.readFile(e,`utf8`)));async function pe({configFile:e}){let t,n=process.cwd(),s=`ikaros.config`,c=[`ts`,`mjs`,`json`,`yaml`].map(e=>`${a(n,s)}.${e}`),l=(await Promise.all(c.map(e=>x.pathExists(e)))).findIndex(Boolean);if(!(l<0)){if(t=i(c[l]),n=o(n,`${s}${t}`),e&&(n=r(e),t=i(e)),!F.has(t))throw Error(`No configuration file ! `);return F.get(t)(n)}}let I=function(e){return e.SERVER=`server`,e.BUILD=`build`,e}({});var L=class{set env(e){this._env=e}get env(){return this._env}set contextPkg(e){this._contextPkg=e}get contextPkg(){return this._contextPkg}get isElectron(){return this.options.platform===`desktopClient`}constructor(t){this.resolveContext=(...e)=>a(this.context,...e);let{command:n,options:r,configFile:i}=t;this.command=n,this.options=r,this.configFile=i,this.context=process.cwd(),this.contextRequire=e(a(this.context,`./`))}static async create(e){let t=new this(e);return await t.initialize(),t}async initialize(){await this.initContextPkg(),await this.initEnv(),await this.loadUserConfig(),await this.onAfterConfigLoaded(),await this.startCompile()}async onAfterConfigLoaded(){}async initContextPkg(){let e=this.resolveContext(`package.json`);try{await u.access(e,l.constants.F_OK)}catch{return}this.contextPkg=JSON.parse(await u.readFile(e,{encoding:`utf8`}))}async initEnv(){let{platform:e,mode:t}=this.options,n={PLATFORM:e,MODE:t},r=await le(t);this.env={...n,...r}}async loadUserConfig(){this.userConfig=await this.getUserConfig()}resolveContextModule(e){try{return this.contextRequire.resolve(e)}catch{return}}loadContextModule(e){return this.contextRequire(e)}async getUserConfig(){let{configFile:e}=this,t=await pe({configFile:e});if(t){if(f(t)){let e={mode:this.options.mode??``,env:{...this.env,PLATFORM:this.options.platform,MODE:this.options.mode??this.env?.MODE},command:this.command};return A.parse(await t(e))}if(g(t))return A.parse(t)}}async startCompile(){switch(this.command){case I.SERVER:await this.dev();break;case I.BUILD:await this.build();break;default:break}}};const R=e=>{let t=`Build failed with errors.
|
|
2
|
+
`;return e.toString({chunks:!1,colors:!0}).split(/\r?\n/).forEach(e=>{t+=` ${e}\n`}),t},z=(e,t)=>{let{onBuildStatus:n}=t??{};return new Promise((t,r)=>{let i=E(e);i.run((e,a)=>{i.close(i=>{let o=e||i;if(o)return n?.({success:!1,message:o.message||`build error`}),r(o);if(a?.hasErrors()){let e=R(a);return n?.({success:!1,message:e}),r(Error(e))}let s=a?.toString({chunks:!1,colors:!0});return n?.({success:!0,message:s}),t(s)})})})},me=async(e,t)=>{let{port:n,onBuildStatus:r}=t??{},i=E(e),a=new ee(e.devServer,i);await new Promise((e,t)=>{a.startCallback(i=>i?(r?.({success:!1,port:n,message:i.message}),t(i)):(r?.({success:!0,port:n}),e()))})},he=(e,t)=>{let{onBuildStatus:n,...r}=t??{};return new Promise((t,i)=>{E(e).watch({ignored:/node_modules/,aggregateTimeout:300,poll:!1,...r},(e,r)=>{if(e)return n?.({success:!1,message:e.message||`watch build error`}),i(e);if(r?.hasErrors()){let e=R(r);return n?.({success:!1,message:e}),i(Error(e))}let a=r?.toString({chunks:!1,colors:!0});return n?.({success:!0,message:a}),t(a)})})},B=b(process.cwd(),`./`),V=[`...`,`.mjs`,`.jsx`,`.ts`,`.tsx`];b(B,`tsconfig.json`);const H=s.fileURLToPath(new s.URL(`../`,import.meta.url)),ge=e(H),U=(...e)=>b(H,...e),W=(e,t)=>({loader:e.includes(`builtin`)?e:ge.resolve(e),options:t}),_e=(e,t)=>{let{lightningcss:n,sourceMap:r}=t??{},i=W(`builtin:lightningcss-loader`,{...n}),a=(e,n)=>{let a=[i],o=t&&t[`${e}`];return e&&e!==`css`&&a.push(W(`${e}-loader`,Object.assign(o??{},n,{sourceMap:r}))),a};return{less:a(`less`),sass:a(`sass`,{sassOptions:{indentedSyntax:!0,api:`modern-compiler`}}),scss:a(`sass`,{sassOptions:{api:`modern-compiler`}}),stylus:a(`stylus`),styl:a(`stylus`),css:a(`css`)}},ve=(e,t)=>{let n=_e(e,t);return Object.entries(n).map(([e,t])=>({test:RegExp(`\\.${e}$`),use:t,type:`css/auto`}))};var G=class{constructor({env:e=`development`,mode:t=``}){this.list=[],this.env=`development`,this.mode=``,this.isDev=!0,this.env=e,this.mode=t,this.isDev=e===`development`}add(e){return e&&(m(e)?this.list=this.list.concat(e):this.list.push(e)),this}end(){return this.list}},K=class extends G{constructor({env:e=`development`,mode:t=``}){super({env:e,mode:t}),this.defaultScriptLoader=e=>[{test:/\.m?ts$/i,loader:`builtin:swc-loader`,options:{jsc:{parser:{syntax:`typescript`}}},type:`javascript/auto`,exclude:[b(B,`node_modules`)]},{test:/\.m?js$/i,loader:`builtin:swc-loader`,options:{isModule:`unknown`,rspackExperiments:e},type:`javascript/auto`,exclude:[b(B,`node_modules`)]}],this.defaultResourceLoader=[{test:/\.(png|jpe?g|gif|svg|ico)(\?.*)?$/,type:`asset/resource`,generator:{filename:this.isDev?`[id][ext]`:`assets/img/[contenthash][ext]`}},{test:/\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,type:`asset/resource`,generator:{filename:this.isDev?`[id][ext]`:`assets/media/[contenthash][ext]`}},{test:/\.(woff2?|eot|ttf|otf)(\?.*)?$/,type:`asset/resource`,generator:{filename:this.isDev?`[id][ext]`:`assets/fonts/[contenthash][ext]`}}]}useDefaultCssLoader(e){return ve(this.env,e).forEach(e=>this.add(e)),this}useDefaultScriptLoader(e){return this.add(this.defaultScriptLoader(e)),this}useDefaultResourceLoader(){return this.defaultResourceLoader.forEach(e=>this.add(e)),this}},q=class extends G{constructor({env:e=`development`,mode:t=``}){super({env:e,mode:t})}useDefaultEnvPlugin(e){let{frameworkEnv:t={},extEnv:n={},env:r={}}=e??{};return this.add(be({frameworkEnv:t,extEnv:n,env:r})),this}useCopyPlugin(){return this.env===`production`&&this.add(new E.CopyRspackPlugin({patterns:[{context:b(B,`public`),from:`./`,noErrorOnMissing:!0,globOptions:{ignore:[`**/index.html`,`.*`]}}]})),this}useHtmlPlugin(e){return this.add(new E.HtmlRspackPlugin({template:e??b(B,`index.html`)})),this}},ye=class{constructor({pages:e,enablePages:t}){this.pages=e,this.enablePages=t,this.getEnablePages()}create(){let e={},t=[];return Object.keys(this.pages).forEach(n=>{e[n]={import:this.pages[n].entry,library:this.pages[n].library},t.push(new E.HtmlRspackPlugin({template:this.pages[n].html,filename:`${n}.html`,chunks:[n],scriptLoading:`blocking`,...this.pages[n].options}))}),{entry:e,plugins:t}}getEnablePages(){let{warning:e,emitEvent:t}=M();if(!h(this.pages)&&m(this.enablePages)){let n={},r=[];if(this.enablePages.forEach(e=>{this.pages[e]?n[e]=this.pages[e]:r.push(e)}),h(r)&&t(e({text:`当前设置页面${r.join()}不存在`,onlyText:!0})),h(n))return;this.pages=n}}};const be=({frameworkEnv:e={},extEnv:t={},env:n={}})=>{let r=Object.assign({},O(t,n)),i=Object.fromEntries(Object.entries(r).map(([e,t])=>[`import.meta.env.${e}`,JSON.stringify(t)])),a=Object.fromEntries(Object.entries({...i,...e}).map(([e,t])=>[e,t]));return new E.DefinePlugin(a)},J=`@rspack/ikaros-cdn-plugin`,Y=/:([a-z]+)/gi;var xe=class{constructor(e){this.isDev=!1,this.options={prodUrl:`https://unpkg.com/:name@:version/:path`,devUrl:`:name/:path`,crossOrigin:!1,...e}}apply(e){this.compiler=e,this.isDev=e.options.mode===`development`,this.handleExternals(),e.hooks.compilation.tap(J,e=>{E.HtmlRspackPlugin.getCompilationHooks(e).alterAssetTags.tapAsync(J,(e,t)=>{try{this.injectResources(e),t(null,e)}catch(e){t(e)}})})}handleExternals(){let e=this.compiler.options.externals||{};this.options.modules.filter(e=>!e.cssOnly).forEach(t=>{e[t.name]=t.var||t.name}),this.compiler.options.externals=e}injectResources(e){let t=this.options.modules,n=[];t.forEach(e=>{this.getStyles(e).forEach(e=>{n.push({tagName:`link`,voidTag:!0,attributes:{rel:`stylesheet`,href:e,...this.options.crossOrigin&&{crossorigin:this.options.crossOrigin}}})})}),t.filter(e=>!e.cssOnly).forEach(e=>{this.getScripts(e).forEach(e=>{n.push({tagName:`script`,voidTag:!0,attributes:{src:e,...this.options.crossOrigin&&{crossorigin:this.options.crossOrigin}}})})}),e.assetTags&&(e.assetTags.styles.unshift(...n.filter(e=>e.tagName===`link`)),e.assetTags.scripts.unshift(...n.filter(e=>e.tagName===`script`)))}getStyles(e){let t=[...e.styles||[]];return e.style&&t.unshift(e.style),t.map(t=>this.generateUrl(e,t))}getScripts(e){let t=[...e.paths||[]];return e.path&&t.unshift(e.path),t.map(t=>this.generateUrl(e,t))}joinUrl(e,t){return e=e.replace(/\/+$/,``),t=t.replace(/^\/+/,``),`${e}/${t}`}generateUrl(e,t){let n=this.isDev?e.devUrl||this.options.devUrl:e.prodUrl||this.options.prodUrl;return n.match(Y)?n.replace(Y,(n,r)=>{switch(r){case`name`:return e.name;case`version`:return e.version||this.getModuleVersion(e.name);case`path`:return t;default:return n}}):this.joinUrl(n,t)}getModuleVersion(t){try{return e(y.join(process.cwd(),`node_modules`))(y.join(t,`package.json`)).version}catch{return console.warn(C.yellow(`[${J}] 无法获取模块 "${t}" 的版本信息`)),`latest`}}},Se=class{constructor(e){this.options=e}createSourceMapPlugin(){let{isDev:e,userConfig:t}=this.options;if(e)return new E.EvalSourceMapDevToolPlugin({columns:!1,module:!0});if(t?.build?.sourceMap??!1)return new E.SourceMapDevToolPlugin({test:[/.js/,/.mjs/],filename:`[file].map[query]`})}createCssExtractPlugin(){if(!this.options.isDev)return new E.CssExtractRspackPlugin({filename:this.joinAssetsDir(`assets/css/[contenthash].css`),ignoreOrder:!0})}createDoctorPlugin(){let{isDev:e,userConfig:t}=this.options;if(!(e||!t?.build?.outReport))return new te}createGzipPlugin(){let{isDev:e,userConfig:t}=this.options;if(!(e||!t?.build?.gzip))return new ne}createCdnPlugin(){let{cdnOptions:e}=this.options.userConfig??{};if(!(!e||h(e.modules)))return new xe(e)}createModuleFederationPlugin(){let e=this.options.userConfig?.moduleFederation;if(e)return m(e)?e.map(e=>new D(e)):new D(e)}createDependencyCyclePlugin(){let{isDev:e,userConfig:t}=this.options;if(!(e||!t?.build?.dependencyCycleCheck))return new E.CircularDependencyRspackPlugin({exclude:/node_modules/,failOnError:!1})}joinAssetsDir(...e){return[this.options.assetsDir,...e].join(`/`).replace(/\/+/g,`/`)}};const Ce=e=>{let{isVue:t,isReact:n}=e;return t?{noParse:/^(vue|vue-router|vuex|vuex-router-sync)$/,env:{__VUE_OPTIONS_API__:!0,__VUE_PROD_DEVTOOLS__:!1,__VUE_PROD_HYDRATION_MISMATCH_DETAILS__:!1}}:n?{noParse:e=>/(react|react-dom|react-is)\.production\.min\.js$/.test(e),env:{REACT_APP_ENABLE_DEVTOOLS:!1}}:{env:void 0,noParse:void 0}},we=e=>e===I.SERVER?{minimize:!1,removeAvailableModules:!1,removeEmptyChunks:!1,splitChunks:!1}:{minimize:!0,minimizer:[new E.LightningCssMinimizerRspackPlugin,new E.SwcJsMinimizerRspackPlugin],splitChunks:{chunks:`all`,minSize:3e4,minChunks:1,maxAsyncRequests:5,maxInitialRequests:3,cacheGroups:{vendor:{test:/[\\/]node_modules[\\/]/,name:`vendors`,priority:10,chunks:`all`},common:{name:`common`,minChunks:2,priority:5,reuseExistingChunk:!0}}}},Te=e=>{if(e.command!==I.SERVER&&e.userConfig?.build?.cache)return{cache:!0,experiments:{cache:{type:`persistent`}}}},Ee=e=>{let{userConfig:t,isElectron:n,resolveContext:r}=e,i=t?.build?.outDirName;if(n){let e=t?.electron,n=r(`dist/electron/renderer`);return e?.build?.outDir?a(r(e.build.outDir),`renderer`):n}return p(i)?r(i):r(`dist`)},X=(e,t)=>[e,t].filter(Boolean).join(`/`).replace(/\/+/g,`/`),De=e=>{let{command:t,mode:n,env:r,context:i,contextPkg:o,userConfig:s,pages:c,browserslist:l,base:u,port:d,isElectron:f,resolveContext:p}=e,m=t===I.SERVER,h=m?`development`:`production`,g=new K({env:h,mode:n}),_=new q({env:h,mode:n}),{entry:v,plugins:y}=new ye({pages:c,enablePages:s?.enablePages}).create(),{env:b,noParse:x}=Ce({isVue:e.isVue,isReact:e.isReact}),S=g.useDefaultResourceLoader().useDefaultScriptLoader(s?.experiments).useDefaultCssLoader(s?.css).add(s?.loaders).end(),C=s?.build?.assetsDir??``,w=new Se({command:t,userConfig:s,isDev:m,assetsDir:C}),T=_.useDefaultEnvPlugin({extEnv:{...s?.define},frameworkEnv:b,env:r}).useCopyPlugin().add(y).add(w.createSourceMapPlugin()).add(w.createCssExtractPlugin()).add(w.createDoctorPlugin()).add(w.createGzipPlugin()).add(w.createCdnPlugin()).add(w.createModuleFederationPlugin()).add(w.createDependencyCyclePlugin()).add(s?.plugins).end();return{mode:h,context:i,entry:v,target:f?`electron-renderer`:[`web`,`es2015`,`browserslist:${l}`],resolve:{alias:{"@":p(`src`),...s?.resolve?.alias},extensions:s?.resolve?.extensions||V,modules:[`node_modules`,p(`node_modules`),U(`node_modules`)]},output:{clean:!0,path:Ee({userConfig:s,isElectron:f,resolveContext:p}),publicPath:f?`./`:u,filename:m?`[name].[contenthash:8].js`:X(C,`assets/js/[contenthash:8].js`),chunkFilename:m?`[name].[contenthash:8].chunk.js`:X(C,`assets/js/[contenthash:8].chunk.js`),chunkLoadingGlobal:`${o?.name||`ikaros`}_chunk`,pathinfo:!1},optimization:we(t),stats:`none`,watchOptions:{aggregateTimeout:500,ignored:/node_modules/},module:{rules:S,noParse:x},plugins:T,devServer:{hot:!0,port:d,server:(()=>{let e=s?.server?.https;return e?e===!0?`https`:{type:`https`,options:e}:`http`})(),allowedHosts:`all`,proxy:s?.server?.proxy,historyApiFallback:{rewrites:[{from:RegExp(`^${u}`),to:a(u,`index.html`)}]},headers:{"Access-Control-Allow-Origin":`*`},static:{directory:p(`public`),publicPath:u},client:{logging:`none`,overlay:{errors:!0,warnings:!1,runtimeErrors:!1},webSocketURL:`auto://0.0.0.0:${d}/ws`}},experiments:{css:!0},...Te({command:t,userConfig:s})}},Oe=e=>{let t=e===`mobile`,n=[`defaults`];return t?n.push(`IOS >= 16`,`Chrome >= 80`):n.push(`>0.2%`,`Chrome >= 90`,`Safari >= 16`,`last 2 versions`,`not dead`),n.join(`,`)},ke=(e,t)=>t?{index:{html:e(`src/renderer/index.html`),entry:e(`src/renderer/index`)}}:{index:{html:e(`index.html`),entry:e(`src/index`)}},Ae=async e=>{let{command:t,resolveContext:n,getUserConfig:r,isElectron:i}=e,a=await r(),o=a?.build?.base??`/`;if(t===I.SERVER&&/^https?:/.test(o)){let e=C.cyan(`build.base`);throw Error(`本地开发时 ${e} 不应该为外部 Host!`)}let s=a?.target??`pc`,c=a?.pages??ke(n,!!i),l=a?.server?.port??await re(`8080`),u=!1,d=!1;try{let[e,t]=await Promise.all([k(`react`),k(`vue`)]);u=t,d=e}catch{}return{userConfig:a,base:o,target:s,pages:c,port:l,browserslist:Oe(s),isVue:u,isReact:d}},Z=async e=>{let{command:t,options:n,env:r,context:i,contextPkg:a,userConfig:o,isElectron:s,resolveContext:c,loadViteAdapter:l}=e,u=await Ae({command:t,resolveContext:c,getUserConfig:async()=>o,isElectron:s}),d=u.userConfig?.bundler??`rspack`;return{bundler:d,config:(()=>{switch(d){case`vite`:{let e=l?.();if(!e)throw Error(`bundler='vite' 需要安装可选依赖 @ikaros-cli/ikaros-bundler-vite`);return e.createWebViteConfig({command:t,mode:n.mode,env:r,context:i,userConfig:u.userConfig,pages:u.pages,base:u.base,port:u.port,isElectron:s,resolveContext:c})}case`rspack`:default:return De({command:t,mode:n.mode,env:r,context:i,contextPkg:a,userConfig:u.userConfig,pages:u.pages,browserslist:u.browserslist,base:u.base,port:u.port,isElectron:s,isVue:u.isVue,isReact:u.isReact,resolveContext:c})}})(),pre:u}},je=()=>{let e=`@ikaros-cli/ikaros-bundler-vite`,t=[`你启用了 bundler='vite',但未安装可选依赖 ${e}。`,``,`请安装后重试:`,` pnpm add -D ${e}`];return Error(t.join(`
|
|
3
|
+
`))},Me=()=>{let e=[`你启用了 bundler='vite',但当前 Node.js 版本过低。`,`当前版本:v${process.versions.node}`,`Vite 7 运行时通常需要 Node.js >= 22。`];return Error(e.join(`
|
|
4
|
+
`))},Q=e=>{let{loadContextModule:t}=e,n=Number(process.versions.node.split(`.`)[0]);if(Number.isFinite(n)&&n<22)throw Me();try{let e=t(`@ikaros-cli/ikaros-bundler-vite`),n=e.default??e;if(typeof n?.createWebViteConfig!=`function`||typeof n?.runViteBuild!=`function`||typeof n?.startViteDevServer!=`function`)throw je();return n}catch(e){throw e instanceof Error,je()}},{error:Ne}=M();var Pe=class extends L{constructor(e){super(e),this.onBuildStatus=e.onBuildStatus}async dev(){let e=await this.prepare();if(e.bundler===`vite`){await e.vite.startViteDevServer(e.config,{port:this.port,onBuildStatus:this.onBuildStatus});return}await me(e.config,{port:this.port,onBuildStatus:this.onBuildStatus})}async build(){let e=await this.prepare();if(e.bundler===`vite`){await e.vite.runViteBuild(e.config,{onBuildStatus:this.onBuildStatus});return}await z(e.config,{onBuildStatus:this.onBuildStatus})}async prepare(){try{let e=await Z({command:this.command,options:this.options,env:this.env,context:this.context,contextPkg:this.contextPkg,userConfig:this.userConfig,isElectron:this.isElectron,resolveContext:this.resolveContext,loadViteAdapter:()=>this.viteAdapter??=Q({loadContextModule:this.loadContextModule.bind(this)})});return this.userConfig=e.pre.userConfig,this.port=e.pre.port,e.bundler===`vite`?{bundler:`vite`,config:e.config,vite:this.viteAdapter??=Q({loadContextModule:this.loadContextModule.bind(this)})}:(console.log(`config`,e.config),{bundler:`rspack`,config:e.config})}catch(e){Ne({text:e instanceof Error?e.message:String(e)}),process.exit(0)}}getDevPort(){return this.port}};const Fe=()=>{let e=`@ikaros-cli/ikaros-platform-desktop-client`,t=[`你启用了 platform='desktopClient',但未安装可选依赖 ${e}。`,``,`请安装后重试:`,` pnpm add -D ${e}`];return Error(t.join(`
|
|
5
|
+
`))},Ie=async()=>{try{let t=await import(c(e(a(process.cwd(),`./`)).resolve(`@ikaros-cli/ikaros-platform-desktop-client`)).href),n=t.default??t;if(typeof n?.startDesktopClientCompile!=`function`)throw Fe();return n}catch{throw Fe()}},$={WEB:`web`,DESKTOPCLIENT:`desktopClient`,ELECTRON:`desktopClient`},Le=[new t(`-m, --mode <name>`,`Environment variable`),new t(`-p, --platform <type>`,`build platform type`).default($.WEB).choices(Object.values($))],Re=async e=>{try{switch(e.options.platform){case $.WEB:await Pe.create(e);return;case $.DESKTOPCLIENT:await(await Ie()).startDesktopClientCompile(e);return;default:{let e=Object.values($).join(`,`);throw Error(`No corresponding compilation service was found, platform: ${e}`)}}}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}\n`),process.exit(1)}},ze=e=>{let t=e.command(I.SERVER,{isDefault:!0}).description(`Start local develop serve`).action(async e=>{await Re({command:I.SERVER,options:e})}),n=e.command(I.BUILD).description(`Start build`).action(async e=>{await Re({command:I.BUILD,options:e})});for(let e of Le)t.addOption(e),n.addOption(e)},Be=e=>e;if(Number(process.versions.node.split(`.`)[0])<22){let e=C.bgRed.white(` ERROR `);process.stderr.write(`${e} Node.js version must be greater than or equal to v22!\n\n`),process.exit(1)}n.version(ie,`-v, --version`),ze(n),n.parse();export{L as BaseCompileService,I as Command,K as CreateLoader,q as CreatePlugins,M as LoggerSystem,Pe as WebCompileService,Be as defineConfig,V as extensions,Q as loadOptionalViteAdapter,Z as prepareWebCompile,U as resolveCLI,z as runRspackBuild,he as watchRspackBuild};
|
package/package.json
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ikaros-cli/ikaros",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "2.1.0",
|
|
4
4
|
"description": "",
|
|
5
|
+
"type": "module",
|
|
5
6
|
"publishConfig": {
|
|
6
7
|
"registry": "https://registry.npmjs.org/",
|
|
7
8
|
"access": "public"
|
|
@@ -14,6 +15,11 @@
|
|
|
14
15
|
"bugs": {
|
|
15
16
|
"url": "https://github.com/umbrella22/ikaros/issues"
|
|
16
17
|
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"dev": "tsdown --watch",
|
|
20
|
+
"dts": "tsdown --dts",
|
|
21
|
+
"build": "tsdown"
|
|
22
|
+
},
|
|
17
23
|
"keywords": [
|
|
18
24
|
"vue",
|
|
19
25
|
"rspack"
|
|
@@ -32,47 +38,39 @@
|
|
|
32
38
|
"readme.md"
|
|
33
39
|
],
|
|
34
40
|
"engines": {
|
|
35
|
-
"node": ">=
|
|
41
|
+
"node": ">=22.0.0",
|
|
36
42
|
"npm": ">=9.5.0"
|
|
37
43
|
},
|
|
38
44
|
"dependencies": {
|
|
39
|
-
"@module-federation/enhanced": "^0.
|
|
40
|
-
"@rsdoctor/rspack-plugin": "^1.
|
|
41
|
-
"@rspack/core": "^1.
|
|
42
|
-
"@rspack/dev-server": "^1.1.
|
|
43
|
-
"chalk": "^5.
|
|
45
|
+
"@module-federation/enhanced": "^0.21.6",
|
|
46
|
+
"@rsdoctor/rspack-plugin": "^1.3.15",
|
|
47
|
+
"@rspack/core": "^1.6.7",
|
|
48
|
+
"@rspack/dev-server": "^1.1.4",
|
|
49
|
+
"chalk": "^5.6.2",
|
|
44
50
|
"cli-cursor": "^5.0.0",
|
|
45
|
-
"commander": "^14.0.
|
|
51
|
+
"commander": "^14.0.2",
|
|
46
52
|
"compression-webpack-plugin": "^11.1.0",
|
|
47
53
|
"css-loader": "^7.1.2",
|
|
48
54
|
"detect-port": "^2.1.0",
|
|
49
|
-
"dotenv": "^17.2.
|
|
55
|
+
"dotenv": "^17.2.3",
|
|
50
56
|
"easy-table": "^1.2.0",
|
|
51
|
-
"
|
|
52
|
-
"fs-extra": "^11.3.
|
|
53
|
-
"glob": "^
|
|
57
|
+
"es-toolkit": "^1.43.0",
|
|
58
|
+
"fs-extra": "^11.3.2",
|
|
59
|
+
"glob": "^13.0.0",
|
|
54
60
|
"less-loader": "^12.3.0",
|
|
55
|
-
"
|
|
56
|
-
"ora": "^
|
|
61
|
+
"listr2": "^9.0.5",
|
|
62
|
+
"ora": "^9.0.0",
|
|
63
|
+
"oxc-transform": "^0.103.0",
|
|
57
64
|
"picocolors": "^1.1.1",
|
|
58
|
-
"pretty-bytes": "^7.
|
|
59
|
-
"
|
|
60
|
-
"
|
|
61
|
-
"stylelint-webpack-plugin": "^5.0.1",
|
|
62
|
-
"stylus-loader": "^8.1.1",
|
|
65
|
+
"pretty-bytes": "^7.1.0",
|
|
66
|
+
"sass-loader": "^16.0.6",
|
|
67
|
+
"stylus-loader": "^8.1.2",
|
|
63
68
|
"vue-style-loader": "^4.1.3",
|
|
64
|
-
"yaml": "^2.8.
|
|
65
|
-
"zod": "^4.
|
|
66
|
-
"@ikaros-cli/infra-contrlibs": "1.4.0"
|
|
69
|
+
"yaml": "^2.8.2",
|
|
70
|
+
"zod": "^4.1.13"
|
|
67
71
|
},
|
|
68
72
|
"devDependencies": {
|
|
69
73
|
"@types/fs-extra": "^11.0.4",
|
|
70
|
-
"@types/minimist": "^1.2.5",
|
|
71
74
|
"vitest": "^3.2.4"
|
|
72
|
-
},
|
|
73
|
-
"scripts": {
|
|
74
|
-
"dev": "tsdown --watch",
|
|
75
|
-
"dts": "tsdown --dts",
|
|
76
|
-
"build": "tsdown"
|
|
77
75
|
}
|
|
78
|
-
}
|
|
76
|
+
}
|
package/readme.md
CHANGED
|
@@ -1,4 +1,42 @@
|
|
|
1
|
-
# ikaros-
|
|
1
|
+
# @ikaros-cli/ikaros 使用文档
|
|
2
|
+
|
|
3
|
+
## 平台
|
|
4
|
+
|
|
5
|
+
ikaros 支持多个运行平台:
|
|
6
|
+
|
|
7
|
+
- `web`:默认平台(本文件后续的大部分配置项均属于 web/Rspack 编译配置)
|
|
8
|
+
- `desktopClient`:Electron 平台(可选依赖,启用时才会从项目依赖中按需加载)
|
|
9
|
+
|
|
10
|
+
### desktopClient(Electron,可选依赖)
|
|
11
|
+
|
|
12
|
+
desktopClient 平台的编译实现位于独立包 `@ikaros-cli/ikaros-platform-desktop-client`。
|
|
13
|
+
|
|
14
|
+
当你使用 `--platform desktopClient` 运行时,请在你的业务项目中安装:
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pnpm add -D @ikaros-cli/ikaros-platform-desktop-client electron
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
示例:
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
ikaros --platform desktopClient --mode development
|
|
24
|
+
ikaros build --platform desktopClient --mode release
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
如果缺少该可选依赖,ikaros 会在运行时提示你安装它。
|
|
28
|
+
|
|
29
|
+
### bundler=vite(可选依赖)
|
|
30
|
+
|
|
31
|
+
如果你选择使用 Vite bundler,仍需要额外安装可选依赖(并遵循其 Node 版本要求):
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pnpm add -D @ikaros-cli/ikaros-bundler-vite
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## ikaros-web 配置项
|
|
2
40
|
|
|
3
41
|
## target
|
|
4
42
|
|