@ikaros-cli/ikaros 1.0.0 → 1.1.1

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/bin.mjs ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import "./dist/index.mjs";
@@ -0,0 +1,232 @@
1
+ import * as https from 'https';
2
+ import * as _rspack_dev_server from '@rspack/dev-server';
3
+ import * as _rspack_core from '@rspack/core';
4
+ import { LightningcssLoaderOptions, ModuleFederationPluginOptions, DefinePluginOptions, Plugin, Loader } from '@rspack/core';
5
+
6
+ interface ImportMetaBaseEnv {
7
+ /** 命令行所指定的 mode (-m, --mode) */
8
+ MODE?: string
9
+ /** 路径前缀 */
10
+ BASE?: string
11
+ /** 平台 */
12
+ PLATFORM: 'web'
13
+ }
14
+
15
+ type ImportMetaEnv = Record<string, any>
16
+
17
+ interface ImportMeta {
18
+ readonly env: Readonly<ImportMetaEnv & ImportMetaBaseEnv>
19
+ }
20
+
21
+ /** 命令 */
22
+ declare const enum Command {
23
+ SERVER = "server",
24
+ BUILD = "build"
25
+ }
26
+
27
+ interface CssLoaderOptions {
28
+ lightningcss?: LightningcssLoaderOptions;
29
+ sourceMap?: boolean;
30
+ less?: Record<string, any>;
31
+ sass?: Record<string, any>;
32
+ stylus?: Record<string, any>;
33
+ }
34
+
35
+ type RspackExperiments = {
36
+ import: Record<string, any>[];
37
+ };
38
+ type Pages = {
39
+ [key: string]: {
40
+ html: string;
41
+ entry: string;
42
+ library?: _rspack_core.LibraryOptions;
43
+ options?: {
44
+ title: string;
45
+ inject: boolean;
46
+ meta: Record<string, any>;
47
+ };
48
+ };
49
+ };
50
+
51
+ interface CdnModule {
52
+ name: string;
53
+ var?: string;
54
+ version?: string;
55
+ path?: string;
56
+ paths?: string[];
57
+ style?: string;
58
+ styles?: string[];
59
+ cssOnly?: boolean;
60
+ prodUrl?: string;
61
+ devUrl?: string;
62
+ }
63
+ interface CdnPluginOptions {
64
+ modules: CdnModule[];
65
+ prodUrl?: string;
66
+ devUrl?: string;
67
+ crossOrigin?: boolean | string;
68
+ sri?: boolean;
69
+ }
70
+
71
+ /**
72
+ * 这里复写了 ModuleFederationPluginOptions,因为 ModuleFederationPluginOptions 是从 module-federation/sdk 导入的,remoteType和rspack的remoteType不一样
73
+ */
74
+ interface ModuleFederationOptions extends Omit<ModuleFederationPluginOptions, 'remoteType'> {
75
+ 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';
76
+ }
77
+ interface UserConfig {
78
+ /**
79
+ * 编译的平台,该值影响底层优化逻辑
80
+ * @default 'pc'
81
+ * @future 该功能受限,目前仅支持 'pc'
82
+ */
83
+ target?: 'pc' | 'mobile';
84
+ /**
85
+ * 页面配置
86
+ * @default
87
+ * {
88
+ * index: {
89
+ * html: path.join(context, 'index.html'),
90
+ * entry: path.join(context, 'src/index')
91
+ * }
92
+ * }
93
+ */
94
+ pages?: Pages;
95
+ /**
96
+ * 可选页面启动,当pages为多个对象时,可选择启动哪些页面,当设置为false或者不设置时,启动所有页面
97
+ * @default false
98
+ */
99
+ enablePages?: string[] | false;
100
+ /**
101
+ * 全局变量
102
+ * @default {}
103
+ */
104
+ define?: DefinePluginOptions;
105
+ /**
106
+ * 模块联邦
107
+ * @see {@link https://module-federation.io/zh/blog/announcement.html}
108
+ * @default undefined
109
+ */
110
+ moduleFederation?: ModuleFederationOptions | ModuleFederationOptions[];
111
+ /**
112
+ * 插件
113
+ * @see {@link https://rspack.dev/zh/guide/features/plugin}
114
+ */
115
+ plugins?: Plugin | Plugin[];
116
+ /**
117
+ * loader
118
+ * @see {@link https://rspack.dev/zh/guide/features/loader}
119
+ */
120
+ loaders?: Loader[];
121
+ /**
122
+ * RspackExperiments
123
+ * @default undefined
124
+ * @see {@link https://rspack.dev/zh/guide/features/builtin-swc-loader#rspackexperimentsimport}
125
+ * @see {@link rules https://www.npmjs.com/package/babel-plugin-import}
126
+ */
127
+ experiments?: RspackExperiments;
128
+ /**
129
+ * cdn配置
130
+ * @default undefined
131
+ * @see {@link https://www.npmjs.com/package/webpack-cdn-plugin}
132
+ */
133
+ cdnOptions?: CdnPluginOptions;
134
+ /**
135
+ * dev 服务相关 该对象下的值不影响 生产环境
136
+ */
137
+ server?: {
138
+ /**
139
+ * 服务器端口号 空则自动获取
140
+ * @default undefined
141
+ */
142
+ port?: number;
143
+ /**
144
+ * webpack-server 服务器代理
145
+ * @see {@link https://webpack.js.org/configuration/dev-server/#devserverproxy}
146
+ * @default undefined
147
+ */
148
+ proxy?: _rspack_dev_server.Configuration['proxy'];
149
+ /**
150
+ * https
151
+ * @see {@link https://webpack.js.org/configuration/dev-server/#devserverhttps}
152
+ * @default false
153
+ */
154
+ https?: boolean | https.ServerOptions;
155
+ };
156
+ /**
157
+ * css loader 配置
158
+ * @see {@link lightningcssOptions https://rspack.dev/zh/guide/features/builtin-lightningcss-loader#%E9%80%89%E9%A1%B9}
159
+ * @see {@link stylusOptions https://webpack.js.org/loaders/stylus-loader/#options}
160
+ * @see {@link lessOptions https://webpack.js.org/loaders/less-loader/#options}
161
+ * @see {@link sassOptions https://webpack.js.org/loaders/sass-loader/#options}
162
+ */
163
+ css?: CssLoaderOptions;
164
+ /**
165
+ * 构建配置
166
+ */
167
+ build?: {
168
+ /**
169
+ * 资源前缀,值得注意的是 './' 只会被原封不动的作为所有资源的前缀,如果你想根据html定位应该填 'auto'
170
+ * @default '/'
171
+ */
172
+ base?: string;
173
+ /**
174
+ * 资产包裹目录,只在生产环境下生效
175
+ * @default undefined
176
+ */
177
+ assetsDir?: string;
178
+ /**
179
+ * 是否输出Gzip版,只在生产环境下生效
180
+ * @default false
181
+ */
182
+ gzip?: boolean;
183
+ /**
184
+ * 生成映射源代码文件,只在生产环境下生效
185
+ * @default false
186
+ */
187
+ sourceMap?: boolean;
188
+ /**
189
+ * 输出的目录名称,只在生产环境下生效
190
+ * @default "dist"
191
+ */
192
+ outDirName?: string;
193
+ /**
194
+ * 是否输出打包分析报告,只在生产环境下生效
195
+ * @default false
196
+ */
197
+ outReport?: boolean;
198
+ /**
199
+ * 是否缓存编译结果
200
+ * @default false
201
+ */
202
+ cache?: boolean;
203
+ };
204
+ /**
205
+ * resolve
206
+ */
207
+ resolve?: {
208
+ /**
209
+ * 路径别名
210
+ * @see {@link https://webpack.js.org/configuration/resolve/#resolvealias}
211
+ * @default {'@': path.join(context,'src')}
212
+ */
213
+ alias?: Record<string, string>;
214
+ /**
215
+ * 默认后缀
216
+ * @see {@link https://webpack.js.org/configuration/resolve/#resolveextensions}
217
+ * @default [".js", ".json", ".wasm",'.mjs', '.jsx', '.ts', '.tsx']
218
+ */
219
+ extensions?: string[];
220
+ };
221
+ }
222
+ type ConfigEnvPre = Readonly<{
223
+ mode: string;
224
+ env: Omit<ImportMeta['env'], 'BASE'>;
225
+ command: Command;
226
+ }>;
227
+ type UserConfigFn<C> = (envPre: ConfigEnvPre) => C | Promise<C>;
228
+ type UserConfigWebExport = UserConfig | Promise<UserConfig> | UserConfigFn<UserConfig>;
229
+ /** 辅助工具函数 */
230
+ declare const defineConfig: (config: UserConfigWebExport) => UserConfigWebExport;
231
+
232
+ export { type ConfigEnvPre, type ModuleFederationOptions, type UserConfig, type UserConfigFn, type UserConfigWebExport, defineConfig };
package/dist/index.mjs ADDED
@@ -0,0 +1,13 @@
1
+ var _e=Object.defineProperty;var r=(o,e)=>_e(o,"name",{value:e,configurable:!0}),I=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});import{program as G}from"commander";var K="@ikaros-cli/ikaros",k="1.1.0";import{Option as De}from"commander";import ft from"chalk";import{rspack as b}from"@rspack/core";import{RsdoctorRspackPlugin as ht}from"@rsdoctor/rspack-plugin";import vt from"compression-webpack-plugin";import{ModuleFederationPlugin as ke}from"@module-federation/enhanced/rspack";import{isEmpty as yt,isString as Re,isArray as Ct}from"radash";import{RspackDevServer as xt}from"@rspack/dev-server";import{join as Oe}from"node:path";import{detect as bt}from"detect-port";import{createRequire as Ye}from"node:module";import{join as le}from"path";import Ke from"node:fs";import pe from"node:fs/promises";import{isObject as Fe}from"radash";import Z from"fs/promises";import{z as i}from"zod";import{join as Ie}from"path";var A=r((o,e)=>{for(let t in e)o[t]=Fe(e[t])&&t in o?A(o[t],e[t]):e[t];return o},"mergeUserConfig");async function N(o){try{let e=Ie(process.cwd(),"node_modules",o);return await Z.access(e,Z.constants.F_OK),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}r(N,"checkDependency");var X=i.object({target:i.enum(["pc","mobile"]).optional().default("pc"),pages:i.custom().optional(),enablePages:i.union([i.array(i.string()),i.boolean()]).optional().default(!1),moduleFederation:i.union([i.custom(),i.array(i.custom())]).optional(),plugins:i.union([i.custom(),i.array(i.custom())]).optional(),loaders:i.array(i.custom()).optional(),experiments:i.custom().optional(),cdnOptions:i.custom().optional(),server:i.object({port:i.number().int().min(1024).max(65535).optional(),proxy:i.custom().optional(),https:i.union([i.boolean(),i.record(i.any())]).optional().default(!1)}).optional(),css:i.object({lightningcssOptions:i.record(i.any()).optional(),sourceMap:i.boolean().optional(),lessOptions:i.record(i.unknown()).optional(),sassOptions:i.record(i.unknown()).optional(),stylusOptions:i.record(i.unknown()).optional()}).optional(),build:i.object({base:i.string().optional().default("/"),assetsDir:i.string().optional(),gzip:i.boolean().optional().default(!1),sourceMap:i.boolean().optional().default(!1),outDirName:i.string().optional().default("dist"),outReport:i.boolean().optional().default(!1),cache:i.boolean().optional().default(!1)}).optional(),resolve:i.object({alias:i.record(i.string()).optional(),extensions:i.array(i.string()).optional()}).optional()});import{dirname as Ae,extname as z,isAbsolute as Ne,join as ze,resolve as ee}from"node:path";import{pathToFileURL as V}from"node:url";import{createRequire as Ve}from"node:module";import{parse as He}from"yaml";import Q from"node:fs";import te from"node:fs/promises";import se from"fs-extra";import{build as Be}from"esbuild";async function qe(o,e=!1){let t=await Be({absWorkingDir:process.cwd(),entryPoints:[o],outfile:"out.js",write:!1,platform:"node",bundle:!0,format:e?"esm":"cjs",sourcemap:"inline",metafile:!0,plugins:[{name:"externalize-deps",setup(n){n.onResolve({filter:/.*/},l=>{let a=l.path;if(!a.startsWith(".")&&!Ne(a))return{external:!0}})}}]}),{text:s}=t.outputFiles[0];return{code:s,dependencies:t.metafile?Object.keys(t.metafile.inputs):[]}}r(qe,"transformConfig");var P=Ve(V(ee()));async function Je(o,e,t=!1){if(t){let u=`${o}.timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`,m=`${u}.mjs`,p=`${V(u)}.mjs`;await te.writeFile(m,e);try{return(await import(p)).default}finally{Q.unlink(m,()=>{})}}let s=z(o),n=Q.realpathSync(o),l=s in P.extensions?s:".js",a=P.extensions[l];P.extensions[l]=(u,m)=>{m===n?u._compile(e,m):a(u,m)},delete I.cache[I.resolve(o)];let c=P(o);return P.extensions[l]=a,c.__esModule?c.default:c}r(Je,"requireConfig");async function We(o,e=!1){let{code:t}=await qe(o,e);return Je(o,t,e)}r(We,"resultConfig");var v=new Map;v.set(".mjs",async o=>(await import(V(o).href)).default);v.set(".ts",async o=>await We(o,!0));v.set(".json",async o=>await se.readJson(o));v.set(".yaml",async o=>{let e=await te.readFile(o,"utf8");return He(e)});async function oe({configFile:o}){let e,t=process.cwd(),s="ikaros.config",n=["ts","mjs","json","yaml"].map(c=>`${ze(t,s)}.${c}`),a=(await Promise.all(n.map(c=>se.pathExists(c)))).findIndex(Boolean);if(!(a<0)){if(e=z(n[a]),t=ee(t,`${s}${e}`),o&&(t=Ae(o),e=z(o)),!v.has(e))throw new Error("No configuration file ! ");return v.get(e)(t)}}r(oe,"resolveConfig");import{isFunction as Ze,isObject as Xe}from"radash";import H from"fs-extra";import{join as B}from"path";import{config as re}from"dotenv";import ne from"chalk";var ie=r(o=>{console.log(`
2
+ `+ne.bgRed.white(" ERROR ")+" "+o)},"errorLog");var y=r(o=>{console.log(`
3
+ `+ne.bgYellow.white(" WARNING ")+" "+o)},"warningLog");var R=r(o=>o?B(q,"env",`.env.${o}`):B(q,"env",".env"),"getEnvPath"),Ge=r(async o=>{if(!await H.pathExists(B(q,"env")))return y("env folder not found"),!1;if(o){if(!await H.pathExists(R(o)))return y(`.env.${o} file not found`),!1}else return await H.pathExists(R())?!0:(y(".env file not found"),!1);return!0},"checkEnv"),q=process.cwd(),ae=r(async o=>await Ge(o)?o?re({path:R(o)}).parsed??{}:re({path:R()}).parsed??{}:{},"getEnv");var O=class{static{r(this,"BaseCompileService")}set env(e){this._env=e}get env(){return this._env}set contextPkg(e){this._contextPkg=e}get contextPkg(){return this._contextPkg}constructor(e){let{command:t,options:s,configFile:n}=e;this.command=t,this.options=s,this.configFile=n,this.context=le(process.cwd(),"./"),this.contextRequire=Ye(this.context),this.initialize()}async initialize(){await this.initContextPkg(),await this.initEnv(),await this.getUserConfig(),this.startCompile()}resolveContext(...e){return le(this.context,...e)}async initContextPkg(){let e=this.resolveContext("package.json");try{await pe.access(e,Ke.constants.F_OK)}catch{return}this.contextPkg=JSON.parse(await pe.readFile(e,{encoding:"utf8"}))}async initEnv(){let{platform:e,mode:t}=this.options,s={PLATFORM:e,MODE:t},n=await ae(t);this.env={...s,...n}}resolveContextModule(e){try{return this.contextRequire.resolve(e)}catch{return}}loadContextModule(e){return this.contextRequire(e)}async getUserConfig(){let{configFile:e}=this,t=await oe({configFile:e}),s;if(t){if(Ze(t)){let n={PLATFORM:this.options.platform},l={mode:this.options.mode??"",env:Object.assign(n,this.env),command:this.command};s=await t(l)}Xe(t)&&(s=t),this.userConfig=X.parse(s)}}startCompile(){switch(this.command){case"server":{this.dev?.();break}case"build":{this.build?.();break}default:break}}};import{join as J}from"path";import{createRequire as Qe}from"node:module";import ce from"node:url";var D=J(process.cwd(),"./"),ue=["...",".mjs",".jsx",".ts",".tsx"],ms=J(D,"tsconfig.json"),me=ce.fileURLToPath(new ce.URL("../",import.meta.url)),de=Qe(me),ge=r((...o)=>J(me,...o),"resolveCLI");import{rspack as j}from"@rspack/core";var fe=r((o,e)=>({loader:o.includes("builtin")?o:de.resolve(o),options:e}),"createLoader"),et=r((o,e)=>{let{lightningcss:t,sourceMap:s}=e??{},n=fe("builtin:lightningcss-loader",{...t}),l=r((a,c)=>{let u=[n],m=e&&e[`${a}`];return a&&a!=="css"&&u.push(fe(`${a}-loader`,Object.assign(m??{},c,{sourceMap:s}))),u},"generateLoaders");return{less:l("less"),sass:l("sass",{sassOptions:{indentedSyntax:!0,api:"modern-compiler"}}),scss:l("sass",{sassOptions:{api:"modern-compiler"}}),stylus:l("stylus"),styl:l("stylus"),css:l("css")}},"cssLoaders"),he=r((o,e)=>{let t=et(o,e);return Object.entries(t).map(([s,n])=>({test:new RegExp(`\\.${s}$`),use:n,type:"css/auto"}))},"buildCssLoaders");import{join as ve}from"path";import{isArray as Ce,isEmpty as ye}from"radash";var S=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"}static{r(this,"BaseCreate")}add(e){return Ce(e)?this.list=this.list.concat(e):e&&this.list.push(e),this}end(){return this.list}},L=class extends S{constructor({env:t="development",mode:s=""}){super({env:t,mode:s});this.defaultScriptLoader=r(t=>({test:/\.m?[j]s$/,loader:"builtin:swc-loader",options:{sourceMap:this.isDev,isModule:"unknown",rspackExperiments:t},type:"javascript/auto"}),"defaultScriptLoader");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]"}}]}static{r(this,"CreateLoader")}useDefaultCssLoader(t){return he(this.env,t).forEach(n=>this.add(n)),this}useDefaultScriptLoader(t){return this.add(this.defaultScriptLoader(t)),this}useDefaultResourceLoader(){return this.defaultResourceLoader.forEach(t=>this.add(t)),this}},T=class extends S{static{r(this,"CreatePlugins")}constructor({env:e="development",mode:t=""}){super({env:e,mode:t})}useDefaultEnvPlugin(e){let{frameworkEnv:t={},extEnv:s={},env:n={}}=e??{};return this.add(tt({frameworkEnv:t,extEnv:s,env:n})),this}useCopyPlugin(){return this.env==="production"&&this.add(new j.CopyRspackPlugin({patterns:[{context:ve(D,"public"),from:"./",noErrorOnMissing:!0,globOptions:{ignore:["**/index.html",".*"]}}]})),this}useHtmlPlugin(e){return this.add(new j.HtmlRspackPlugin({template:e??ve(D,"index.html")})),this}},M=class{static{r(this,"CreateMpaAssets")}constructor({pages:e,enablePages:t}){this.pages=e,this.enablePages=t,this.getEnablePages()}create(){let e={},t=[];return Object.keys(this.pages).forEach(s=>{e[s]={import:this.pages[s].entry,library:this.pages[s].library},t.push(new j.HtmlRspackPlugin({template:this.pages[s].html,filename:`${s}.html`,chunks:[s],scriptLoading:"blocking",...this.pages[s].options}))}),{entry:e,plugins:t}}getEnablePages(){if(!ye(this.pages)&&Ce(this.enablePages)){let e={},t=[];if(this.enablePages.forEach(s=>{this.pages[s]?e[s]=this.pages[s]:t.push(s)}),t.length&&y(`\u5F53\u524D\u8BBE\u7F6E\u9875\u9762${t.join()}\u4E0D\u5B58\u5728`),ye(e))return;this.pages=e}}},tt=r(({frameworkEnv:o={},extEnv:e={},env:t={}})=>{let s=Object.assign({},A(e,t)),n=Object.fromEntries(Object.entries(s).map(([a,c])=>[`import.meta.env.${a}`,JSON.stringify(c)])),l=Object.fromEntries(Object.entries({...n,...o}).map(([a,c])=>[a,c]));return new j.DefinePlugin(l)},"createEnvPlugin");import{rspack as st}from"@rspack/core";import x from"chalk";import ot from"ora";import nt from"node:os";import U from"pretty-bytes";import it from"easy-table";import rt from"cli-cursor";import at from"node:path";import xe from"node:process";import{isArray as lt}from"radash";var be={name:K,version:k},C="@rspack/ikaros-stats-plugin",Pe=x.hex("#222222"),E=class{constructor(e){this.startCompileHrtime=void 0;this.userConfig=e,this.ora=ot({color:"cyan",prefixText:"",hideCursor:!1})}static{r(this,"StatsPlugin")}apply(e){this.compiler=e,this.isDev=e.options.mode==="development",new st.ProgressPlugin(this.progressHandler.bind(this)).apply(e),rt.hide(),this.isDev?this.initDevHook():this.initProdHook()}progressHandler(e,t,...s){let n=`${(e*100).toFixed(2)}%`;n+=` ${t} `,n+=x.gray(s?.join(" ")),this.lastProgressText!==n&&(this.lastProgressText=n,this.isDev?this.ora.text=`${n}
4
+ `:console.log(n))}updateStartCompileTime(){this.startCompileHrtime=xe.hrtime()}getCurrentEndCompileTime(){let e=xe.hrtime(this.startCompileHrtime);return(e[0]*1e9+e[1])/1e6}getError(e){let{errors:t,errorsCount:s=0}=e;if(!(!t||s===0))return t.map(n=>`${Pe.bgRed(" ERROR ")} ${n.message.trim()}`).join(`
5
+
6
+ `)}getWarn(e){let{warnings:t,warningsCount:s=0}=e;if(!(!t||s===0))return t.map(n=>`${Pe.bgYellow(" WARN ")} ${n.message.trim()}`).join(`
7
+
8
+ `)}getEndTips(e,t){let{gray:s,cyan:n,red:l,green:a,yellow:c}=x,{errorsCount:u=-1,warningsCount:m=-1}=e,p=(t/1e3).toFixed(2);return u>0?s(`${n(be.name)} compiled with${l(` ${u} error`)}`):m>0?s(`compile ${a("success")} and with ${c(`${m} warning`)}, time: ${p}s`):s(`compile ${a("success")}, time: ${p}s.`)}getTableInfo(e){let{assets:t}=e;if(!t||t.length===0)return;let s=new it,n=this.userConfig?.build?.gzip??!1,l=0,a=0,c=!1;for(let u=0;u<t.length;u++){let{name:m,size:p,related:d,info:h}=t[u];if(h.development)continue;let g=n&&lt(d)?d.find(f=>f.type==="gzipped").size:0;if(l+=p,a+=g,t.length>20&&u>=4&&u<t.length-1-4){c||(c=!0,s.cell("name","...."),s.cell("size","...."),n&&s.cell("gzip","...."),s.newRow());continue}s.cell("name",m),s.cell("size",U(p)),n&&s.cell("gzip",U(g)),s.newRow()}return s.pushDelimeter(),s.cell("name",`There are ${t.length} files`),s.cell("size",U(l)),n&&s.cell("gzip",U(a)),s.newRow(),x.cyan.dim(s.toString().trim())}getHostList(){let{userConfig:e,compiler:t}=this,{devServer:s}=t.options,n=s?.server==="https"||typeof s?.server=="object",l=Number(s?.port),a=[],c="",u=Object.values(nt.networkInterfaces());if(e){c=e.build?.base??"",(!c||c==="auto")&&(c="/");let p=Object.keys(e?.pages||{})[0];p&&p!=="index"?c=at.join(c,`${p}.html`):c.endsWith("/")||(c+="/")}for(let p of u){let{address:d}=p?.find(h=>h.family==="IPv4")||{};d&&a.push(d)}a.sort((p,d)=>{let h=p.split("."),g=d.split(".");for(let[f]of h.entries())if(p[f]!==g[f])return Number(g[f])-Number(p[f]);return 0});let m=a.indexOf("127.0.0.1");return m!==-1&&(a.splice(m,1),a.unshift("localhost")),a=a.map(p=>(n?(p=`https://${p}`,l!==443&&(p=p+":"+l)):(p="http://"+p,l!==80&&(p=p+":"+l)),new URL(c,p).href)),a}initDevHook(){let{compiler:e,ora:t}=this,s=this.getHostList(),{blue:n,cyan:l,gray:a}=x;e.hooks.environment.intercept({name:C,call(){t.start("Preparing resource files....")}}),e.hooks.watchRun.intercept({name:C,call:r(()=>{t.isSpinning||console.clear(),t.start(),this.updateStartCompileTime()},"call")}),e.hooks.done.intercept({name:C,call:r(c=>{t.stop(),console.clear();let u=c.toJson({preset:"errors-warnings",colors:!0}),{errorsCount:m=0,warningsCount:p=0}=u;if(m>0)console.log(this.getError(u)),console.log();else{p>0&&(console.log(this.getWarn(u)),console.log());let{name:d,version:h}=be,g=`${l(`${d} v${h}`)} entry address:
9
+
10
+ `;for(let f of s)g+=n(` ${f}
11
+ `);console.log(a(g))}console.log(this.getEndTips(u,this.getCurrentEndCompileTime())),console.log()},"call")})}initProdHook(){let{compiler:e}=this,t;e.hooks.environment.intercept({name:C,call:r(()=>{console.log(x.gray("start build...")),this.updateStartCompileTime()},"call")}),e.hooks.done.intercept({name:C,call:r(s=>{t=s.toJson({preset:"normal",colors:!0,assetsSort:"size"})},"call")}),e.cache.hooks.shutdown.intercept({name:C,done:r(()=>{let{errorsCount:s=0,warningsCount:n=0}=t;console.log(),s>0?(console.log(this.getError(t)),console.log()):(n>0&&(console.log(this.getWarn(t)),console.log()),console.log(this.getTableInfo(t)),console.log()),console.log(this.getEndTips(t,this.getCurrentEndCompileTime()))},"done")})}};import{rspack as pt}from"@rspack/core";import{createRequire as ct}from"node:module";import ut from"chalk";import Ee from"path";var W="@rspack/ikaros-cdn-plugin",mt="https://unpkg.com/:name@:version/:path",dt=":name/:path",we=/:([a-z]+)/gi,w=class{constructor(e){this.isDev=!1;this.options={prodUrl:mt,devUrl:dt,crossOrigin:!1,sri:!1,...e}}static{r(this,"CdnPlugin")}apply(e){this.compiler=e,this.isDev=e.options.mode==="development",this.handleExternals(),e.hooks.compilation.tap(W,t=>{pt.HtmlRspackPlugin.getCompilationHooks(t).alterAssetTags.tapAsync(W,(n,l)=>{try{this.injectResources(n),l(null,n)}catch(a){l(a)}})})}handleExternals(){let e=this.compiler.options.externals||{};this.options.modules.filter(t=>!t.cssOnly).forEach(t=>{e[t.name]=t.var||t.name}),this.compiler.options.externals=e}injectResources(e){let t=this.options.modules,s=[];t.forEach(n=>{this.getStyles(n).forEach(a=>{s.push({tagName:"link",voidTag:!0,attributes:{rel:"stylesheet",href:a,...this.options.crossOrigin&&{crossorigin:this.options.crossOrigin}}})})}),t.filter(n=>!n.cssOnly).forEach(n=>{this.getScripts(n).forEach(a=>{s.push({tagName:"script",voidTag:!0,attributes:{src:a,...this.options.crossOrigin&&{crossorigin:this.options.crossOrigin}}})})}),e.assetTags&&(e.assetTags.styles.unshift(...s.filter(n=>n.tagName==="link")),e.assetTags.scripts.unshift(...s.filter(n=>n.tagName==="script")))}getStyles(e){let t=[...e.styles||[]];return e.style&&t.unshift(e.style),t.map(s=>this.generateUrl(e,s))}getScripts(e){let t=[...e.paths||[]];return e.path&&t.unshift(e.path),t.map(s=>this.generateUrl(e,s))}joinUrl(e,t){return e=e.replace(/\/+$/,""),t=t.replace(/^\/+/,""),`${e}/${t}`}generateUrl(e,t){let s=this.isDev?e.devUrl||this.options.devUrl:e.prodUrl||this.options.prodUrl;return s.match(we)?s.replace(we,(n,l)=>{switch(l){case"name":return e.name;case"version":return e.version||this.getModuleVersion(e.name);case"path":return t;default:return n}}):this.joinUrl(s,t)}getModuleVersion(e){try{return ct(Ee.join(process.cwd(),"node_modules"))(Ee.join(e,"package.json")).version}catch{return console.warn(ut.yellow(`[${W}] \u65E0\u6CD5\u83B7\u53D6\u6A21\u5757 "${e}" \u7684\u7248\u672C\u4FE1\u606F`)),"latest"}}};var $=class extends O{constructor(){super(...arguments);this.isVue=!1;this.isReact=!1}static{r(this,"WebCompileService")}async dev(){await this.initPreConfig(),await this.createRspackBuilder({isLive:!0,config:this.rspackConfig})}async build(){await this.initPreConfig(),await this.createRspackBuilder({isLive:!1,config:this.rspackConfig})}async initPreConfig(){await this.initUserConfig(),await this.initBrowserslist(),await this.initOtherConfig(),this.rspackConfig=await this.createRspackConfig()}async initUserConfig(){let t=this.command==="server",s=this.userConfig;if(this.base=s?.build?.base??"/",t&&Re(this.base)&&/^https?:/.test(this.base)){let n=ft.cyan("build.base");ie(`\u672C\u5730\u5F00\u53D1\u65F6 ${n} \u4E0D\u5E94\u8BE5\u4E3A\u5916\u90E8 Host!`),process.exit(0)}this.target=s?.target??"pc",this.pages=s?.pages??{index:{html:this.resolveContext("index.html"),entry:this.resolveContext("src/index")}},this.port=s?.server?.port??await bt("8080")}async initBrowserslist(){let t=this.target==="mobile",s=["defaults"];t?s.push("IOS >= 10","Chrome >= 56"):s.push(">0.2%","Chrome >= 56","Safari >= 10","last 2 versions","not dead"),this.browserslist=s.join(",")}async initOtherConfig(){try{let[t,s]=await Promise.all([N("react"),N("vue")]);this.isVue=s,this.isReact=t}catch{}}joinAssetsDir(...t){let s=this.userConfig?.build?.assetsDir??"";return Oe(s,...t).replaceAll("\\","/")}getOutDirPath(){let t=this.userConfig?.build?.outDirName;return Re(t)?this.resolveContext(t):this.resolveContext("dist")}async createRspackConfig(){let t=this.command==="server",s=t?"development":"production",{userConfig:n,context:l,browserslist:a,pages:c,contextPkg:u,port:m,base:p}=this,d=new L({env:s,mode:this.options.mode}),h=new T({env:s,mode:this.options.mode}),g=new M({pages:c,enablePages:n?.enablePages}),{entry:f,plugins:Le}=g.create(),{env:Te,noParse:Me}=this.createVueOrReactConfig(),Ue=d.useDefaultResourceLoader().useDefaultScriptLoader(n?.experiments).useDefaultCssLoader(n?.css).add(n?.loaders).end(),$e=h.useDefaultEnvPlugin({extEnv:{...n?.define},frameworkEnv:Te,env:this.env}).useCopyPlugin().add(Le).add(new E).add(this.createSourceMapPlugin()).add(this.createCssExtractPlugin()).add(this.createDoctorPlugin()).add(this.createGzipPlugin()).add(this.createCdnPlugin()).add(this.createModuleFederationPlugin()).add(n?.plugins).end();return{mode:s,target:["web","es5",`browserslist:${a}`],context:l,entry:f,resolve:{alias:{"@":this.resolveContext("src"),...n?.resolve?.alias},extensions:n?.resolve?.extensions||ue,modules:["node_modules",this.resolveContext("node_modules"),ge("node_modules")]},output:{clean:!0,path:this.getOutDirPath(),publicPath:p,filename:t?"[id].js":this.joinAssetsDir("assets/js/[contenthash].js"),chunkLoadingGlobal:`${u?.name||"ikaros"}_chunk`,pathinfo:!1},optimization:this.createOptimization(),stats:"none",watchOptions:{aggregateTimeout:500,ignored:/node_modules/},module:{rules:Ue,noParse:Me},plugins:$e,devServer:{hot:!0,port:m,server:(()=>{let F=n?.server?.https;return F?F===!0?"https":{type:"https",options:F}:"http"})(),allowedHosts:"all",proxy:n?.server?.proxy,historyApiFallback:{rewrites:[{from:new RegExp(`^${p}`),to:Oe(p,"index.html")}]},headers:{"Access-Control-Allow-Origin":"*"},static:{directory:this.resolveContext("public"),publicPath:p},client:{logging:"none",overlay:{errors:!0,warnings:!1,runtimeErrors:!1},webSocketURL:`auto://0.0.0.0:${m}/ws`}},experiments:{css:!0},...this.createCacheConfig()}}createSourceMapPlugin(){let{userConfig:t,command:s}=this;if(s==="server")return new b.EvalSourceMapDevToolPlugin({columns:!1,module:!0});if(t?.build?.sourceMap??!1)return new b.SourceMapDevToolPlugin({test:[/.js/,/.mjs/],filename:"[file].map[query]"})}createCssExtractPlugin(){if(this.command!=="server")return new b.CssExtractRspackPlugin({filename:this.joinAssetsDir("assets/css/[contenthash].css"),ignoreOrder:!0})}createDoctorPlugin(){if(this.command!=="server"&&this.userConfig?.build?.outReport)return new ht}createGzipPlugin(){if(this.command!=="server"&&this.userConfig?.build?.gzip)return new vt}createOptimization(){return this.command==="server"?{minimize:!1,removeAvailableModules:!1,removeEmptyChunks:!1,splitChunks:!1}:{minimize:!0,minimizer:[new b.LightningCssMinimizerRspackPlugin,new b.SwcJsMinimizerRspackPlugin],splitChunks:{chunks:"all",minSize:2e4,minChunks:2,maxAsyncRequests:30,maxInitialRequests:30,cacheGroups:{defaultVendors:{test:/[/\\]node_modules[/\\]/,priority:-10,reuseExistingChunk:!0},default:{minChunks:2,priority:-20,reuseExistingChunk:!0}}}}}createCacheConfig(){if(this.command!=="server"&&this.userConfig?.build?.cache)return{cache:!0,experiments:{cache:{type:"persistent"}}}}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:r(t=>/(react|react-dom|react-is)\.production\.min\.js$/.test(t),"noParse"),env:{REACT_APP_ENABLE_DEVTOOLS:!1}}:{env:void 0,noParse:void 0}}createCdnPlugin(){let{cdnOptions:t}=this.userConfig??{};if(!(!t||yt(t.modules)))return new w(t)}createModuleFederationPlugin(){let t=this.userConfig?.moduleFederation;if(t)return Ct(t)?t.map(s=>new ke(s)):new ke(t)}createRspackBuilder({isLive:t,config:s}){return new Promise((n,l)=>{let a=b(s);if(t){new xt(s.devServer,a).startCallback(m=>{if(m)return l(m);n(void 0)});return}let c="";a.run((u,m)=>{a.close(p=>u||p?(console.error(u||p),l(u||p)):m?.hasErrors()?(c+=`Build failed with errors.
12
+ `,m.toString({chunks:!1,colors:!0}).split(/\r?\n/).forEach(d=>{c+=` ${d}
13
+ `}),l(new Error(c))):n(m?.toString({chunks:!1,colors:!0})))})})}};var _={WEB:"web"},Pt=[new De("-m, --mode <name>","Environment variable"),new De("-p, --platform <type>","build platform type").default(_.WEB).choices(Object.values(_))],je=r(o=>{switch(o.options.platform){case _.WEB:{new $(o);break}default:{let e=Object.values(_).join(",");console.error(`No corresponding compilation service was found, platform: ${e}`),process.exit(1)}}},"startCompile"),Se=r(o=>{let e=o.command("server",{isDefault:!0}).description("Start local develop serve").action(s=>{je({command:"server",options:s})}),t=o.command("build").description("Start build").action(s=>{je({command:"build",options:s})});for(let s of Pt)e.addOption(s),t.addOption(s)},"commander");var vo=r(o=>o,"defineConfig");import wt from"chalk";var kt=Number(process.versions.node.split(".")[0]);if(kt<18){let o=wt.bgRed.white(" ERROR ");console.error(o+" The Node.js version is greater than v18!"),console.log(),process.exit(1)}G.version(k,"-v, --version");Se(G);G.parse();export{vo as defineConfig};
package/package.json CHANGED
@@ -1,8 +1,7 @@
1
1
  {
2
2
  "name": "@ikaros-cli/ikaros",
3
- "version": "1.0.0",
3
+ "version": "1.1.1",
4
4
  "description": "",
5
- "type": "module",
6
5
  "publishConfig": {
7
6
  "registry": "https://registry.npmjs.org/",
8
7
  "access": "public"
@@ -15,59 +14,64 @@
15
14
  "bugs": {
16
15
  "url": "https://github.com/umbrella22/ikaros/issues"
17
16
  },
17
+ "scripts": {
18
+ "dev": "tsup --watch",
19
+ "dts": "tsup --dts",
20
+ "build": "tsup"
21
+ },
18
22
  "keywords": [
19
- "electron",
20
23
  "vue",
21
- "vite"
24
+ "rspack"
22
25
  ],
23
26
  "author": "sky <https://github.com/umbrella22>",
24
27
  "license": "MIT",
25
- "main": "dist/cli.js",
26
- "module": "dist/cli.js",
27
- "types": "dist/index.d.ts",
28
+ "main": "dist/index.mjs",
29
+ "module": "dist/index.mjs",
30
+ "types": "dist/index.d.mts",
28
31
  "bin": {
29
- "ikaros": "dist/cli.js"
32
+ "ikaros": "bin.mjs"
30
33
  },
31
34
  "files": [
32
- "dist"
35
+ "dist",
36
+ "bin.mjs",
37
+ "readme.md"
33
38
  ],
34
- "peerDependencies": {
35
- "electron": ">=29.0.0"
36
- },
37
39
  "engines": {
38
- "node": ">=18.0.0",
40
+ "node": ">=20.0.0",
39
41
  "npm": ">=9.5.0"
40
42
  },
41
43
  "dependencies": {
42
- "@rollup/plugin-alias": "^5.1.0",
43
- "@rollup/plugin-commonjs": "^25.0.7",
44
- "@rollup/plugin-json": "^6.1.0",
45
- "@rollup/plugin-node-resolve": "^15.2.3",
46
- "@rollup/plugin-replace": "^5.0.5",
47
- "cac": "^6.7.14",
48
- "chalk": "^5.3.0",
49
- "dotenv": "^16.4.5",
50
- "electron-builder": "^23.6.0",
51
- "esbuild": "^0.19.12",
52
- "fs-extra": "^11.2.0",
53
- "glob": "^10.3.15",
54
- "inquirer": "^9.2.22",
55
- "javascript-obfuscator": "^4.1.0",
56
- "picocolors": "^1.0.1",
57
- "portfinder": "^1.0.32",
58
- "postcss-px-to-viewport-8-plugin": "^1.2.5",
59
- "rollup": "^4.17.2",
60
- "rollup-plugin-esbuild": "^6.1.1",
61
- "rollup-plugin-obfuscator": "^1.1.0",
62
- "vite": "^5.2.11",
63
- "yaml": "^2.4.2"
44
+ "@module-federation/enhanced": "^0.8.12",
45
+ "@rsdoctor/rspack-plugin": "^0.4.13",
46
+ "@rspack/core": "^1.2.7",
47
+ "@rspack/dev-server": "^1.0.10",
48
+ "chalk": "^5.4.1",
49
+ "cli-cursor": "^5.0.0",
50
+ "commander": "^13.1.0",
51
+ "compression-webpack-plugin": "^11.1.0",
52
+ "css-loader": "^7.1.2",
53
+ "detect-port": "^2.1.0",
54
+ "dotenv": "^16.4.7",
55
+ "easy-table": "^1.2.0",
56
+ "esbuild": "^0.21.5",
57
+ "fs-extra": "^11.3.0",
58
+ "glob": "^10.4.5",
59
+ "inquirer": "^9.3.7",
60
+ "less-loader": "^12.2.0",
61
+ "minimist": "^1.2.8",
62
+ "ora": "^8.2.0",
63
+ "picocolors": "^1.1.1",
64
+ "pretty-bytes": "^6.1.1",
65
+ "radash": "^12.1.0",
66
+ "sass-loader": "^16.0.5",
67
+ "stylus-loader": "^8.1.1",
68
+ "vue-style-loader": "^4.1.3",
69
+ "yaml": "^2.7.0",
70
+ "zod": "^3.24.2"
64
71
  },
65
72
  "devDependencies": {
66
- "@types/fs-extra": "^11.0.4"
67
- },
68
- "scripts": {
69
- "dev": "tsup --watch",
70
- "dts": "tsup --dts",
71
- "build": "tsup"
73
+ "@types/fs-extra": "^11.0.4",
74
+ "@types/minimist": "^1.2.5",
75
+ "vitest": "^3.0.7"
72
76
  }
73
77
  }
package/readme.md ADDED
@@ -0,0 +1,272 @@
1
+ # ikaros-web 使用文档
2
+
3
+ ## target
4
+
5
+ 编译的平台,该值影响底层优化逻辑。
6
+
7
+ - 类型: `'pc' | 'mobile'`
8
+ - 默认值: `'pc'`
9
+ - 未来支持: 该功能受限,目前仅支持 `'pc'`
10
+
11
+ ## pages
12
+
13
+ 页面配置。
14
+
15
+ - 类型: `Pages`
16
+ - 默认值:
17
+
18
+ ```json
19
+ {
20
+ "index": {
21
+ "html": "path.join(context, 'index.html')",
22
+ "entry": "path.join(context, 'src/index')"
23
+ }
24
+ }
25
+ ```
26
+
27
+ ## moduleFederation
28
+
29
+ 模块联邦。
30
+
31
+ - 类型: `ModuleFederationOptions | ModuleFederationOptions[]`
32
+ - 默认值: `undefined`
33
+ - 参考: [Module Federation](https://module-federation.io/zh/blog/announcement.html)
34
+
35
+ ## plugins
36
+
37
+ 插件。
38
+
39
+ - 类型: `Plugin | Plugin[]`
40
+ - 参考: [Rspack Plugins](https://rspack.dev/zh/guide/features/plugin)
41
+
42
+ ## loaders
43
+
44
+ loader。
45
+
46
+ - 类型: `Loader[]`
47
+ - 参考: [Rspack Loaders](https://rspack.dev/zh/guide/features/loader)
48
+
49
+ ## experiments
50
+
51
+ RspackExperiments。
52
+
53
+ - 类型: `RspackExperiments`
54
+ - 默认值: `undefined`
55
+ - 参考: [Rspack Experiments](https://rspack.dev/zh/guide/features/builtin-swc-loader#rspackexperimentsimport)
56
+ - 参考: [Babel Plugin Import](https://www.npmjs.com/package/babel-plugin-import)
57
+
58
+ ### cdnOptions
59
+
60
+ - 类型:`CdnPluginOptions`
61
+ - 默认值:`undefined`
62
+ - 说明:用于在构建过程中将外部依赖注入到 HTML 中,支持开发和生产环境使用不同的 CDN 源。
63
+ - 参考:
64
+ - 基础配置:
65
+
66
+ ```typescript
67
+ // filepath: ikaros.config.ts
68
+ import { defineConfig } from '@ikaros-cli/ikaros'
69
+
70
+ export default defineConfig({
71
+ cdnOptions: {
72
+ modules: [
73
+ {
74
+ name: 'vue', // 模块名称
75
+ var: 'Vue', // 全局变量名
76
+ path: 'dist/vue.runtime.min.js', // JS 文件路径
77
+ },
78
+ {
79
+ name: 'element-plus',
80
+ var: 'ElementPlus',
81
+ path: 'dist/index.full.min.js',
82
+ style: 'dist/index.css', // CSS 文件路径
83
+ },
84
+ ],
85
+ // 可选:自定义 CDN URL 模板
86
+ prodUrl: 'https://unpkg.com/:name@:version/:path',
87
+ devUrl: ':name/:path',
88
+ // 可选:启用跨域配置
89
+ crossOrigin: 'anonymous',
90
+ },
91
+ })
92
+ ```
93
+
94
+ #### CDN 配置项说明
95
+
96
+ #### CdnModule 配置
97
+
98
+ | 参数 | 类型 | 必填 | 说明 |
99
+ | ------- | -------- | ---- | -------------------------------------------- |
100
+ | name | string | 是 | 模块名称,需与 package.json 中的名称一致 |
101
+ | var | string | 否 | 模块导出的全局变量名 |
102
+ | version | string | 否 | 指定版本号,未指定时自动从 node_modules 获取 |
103
+ | path | string | 否 | 主 JS 文件路径 |
104
+ | paths | string[] | 否 | 额外的 JS 文件路径列表 |
105
+ | style | string | 否 | 主 CSS 文件路径 |
106
+ | styles | string[] | 否 | 额外的 CSS 文件路径列表 |
107
+ | cssOnly | boolean | 否 | 是否仅加载 CSS 文件 |
108
+ | prodUrl | string | 否 | 指定该模块的生产环境 CDN URL 模板 |
109
+ | devUrl | string | 否 | 指定该模块的开发环境 CDN URL 模板 |
110
+
111
+ #### 插件选项
112
+
113
+ | 参数 | 类型 | 默认值 | 说明 |
114
+ | ----------- | ----------------- | ---------------------------------------- | --------------------- |
115
+ | modules | CdnModule[] | - | CDN 模块配置列表 |
116
+ | prodUrl | string | <https://unpkg.com/:name@:version/:path> | 生产环境 CDN URL 模板 |
117
+ | devUrl | string | :name/:path | 开发环境 CDN URL 模板 |
118
+ | crossOrigin | boolean \| string | false | 跨域资源配置 |
119
+
120
+ #### URL 模板
121
+
122
+ 支持以下占位符:
123
+
124
+ - `:name` - 模块名称
125
+ - `:version` - 模块版本号
126
+ - `:path` - 资源路径
127
+
128
+ #### 使用示例
129
+
130
+ ##### 基础用法
131
+
132
+ ```typescript
133
+ cdnOptions: {
134
+ modules: [
135
+ {
136
+ name: 'vue',
137
+ var: 'Vue',
138
+ path: 'dist/vue.runtime.min.js',
139
+ },
140
+ ]
141
+ }
142
+ ```
143
+
144
+ ##### 使用自定义 CDN
145
+
146
+ ```typescript
147
+ cdnOptions: {
148
+ modules: [
149
+ {
150
+ name: "vue",
151
+ var: "Vue",
152
+ path: "dist/vue.runtime.min.js",
153
+ },
154
+ ];
155
+ // 仅在生产环境时生效
156
+ prodUrl: "https://cdn.jsdelivr.net/npm/:name@:version/:path",
157
+ }
158
+ ```
159
+
160
+ ##### 加载多个资源
161
+
162
+ ```typescript
163
+ cdnOptions: {
164
+ modules: [
165
+ {
166
+ name: 'element-plus',
167
+ var: 'ElementPlus',
168
+ path: 'dist/index.full.min.js',
169
+ paths: ['dist/locale/zh-cn.min.js'],
170
+ style: 'dist/index.css',
171
+ styles: ['dist/theme-chalk/dark.css'],
172
+ },
173
+ ]
174
+ }
175
+ ```
176
+
177
+ ##### 仅加载样式
178
+
179
+ ```typescript
180
+ cdnOptions: {
181
+ modules: [
182
+ {
183
+ name: 'normalize.css',
184
+ style: 'normalize.css',
185
+ cssOnly: true,
186
+ },
187
+ ]
188
+ }
189
+ ```
190
+
191
+ #### 注意事项
192
+
193
+ 1. 确保模块名称与 package.json 中的名称一致
194
+ 2. 建议在生产环境中明确指定版本号
195
+ 3. 使用自定义 CDN 时注意资源路径的正确性
196
+ 4. 开发环境默认使用本地 node_modules 中的文件
197
+
198
+ ## server
199
+
200
+ dev 服务相关,该对象下的值不影响生产环境。
201
+
202
+ - 类型: `object`
203
+ - `port`: 服务器端口号,空则自动获取。
204
+ - 类型: `number`
205
+ - 默认值: `undefined`
206
+ - `proxy`: webpack-server 服务器代理。
207
+ - 类型: `import('@rspack/dev-server').Configuration['proxy']`
208
+ - 默认值: `undefined`
209
+ - 参考: [DevServer Proxy](https://webpack.js.org/configuration/dev-server/#devserverproxy)
210
+ - `https`: https 配置。
211
+ - 类型: `boolean | import('https').ServerOptions`
212
+ - 默认值: `false`
213
+ - 参考: [DevServer HTTPS](https://webpack.js.org/configuration/dev-server/#devserverhttps)
214
+
215
+ ## css
216
+
217
+ css loader 配置。
218
+
219
+ - 类型: `CssLoaderOptions`
220
+ - 参考: [LightningCSS Options](https://rspack.dev/zh/guide/features/builtin-lightningcss-loader#%E9%80%89%E9%A1%B9)
221
+ - 参考: [Stylus Options](https://webpack.js.org/loaders/stylus-loader/#options)
222
+ - 参考: [Less Options](https://webpack.js.org/loaders/less-loader/#options)
223
+ - 参考: [Sass Options](https://webpack.js.org/loaders/sass-loader/#options)
224
+
225
+ ## build
226
+
227
+ 构建配置。
228
+
229
+ - 类型: `object`
230
+ - `base`: 资源前缀,值得注意的是 `'./'` 只会被原封不动的作为所有资源的前缀,如果你想根据 html 定位应该填 `'auto'`。
231
+ - 类型: `string`
232
+ - 默认值: `'/'`
233
+ - `assetsDir`: 资产包裹目录,只在生产环境下生效。
234
+ - 类型: `string`
235
+ - 默认值: `undefined`
236
+ - `gzip`: 是否输出 Gzip 版,只在生产环境下生效。
237
+ - 类型: `boolean`
238
+ - 默认值: `false`
239
+ - `sourceMap`: 生成映射源代码文件,只在生产环境下生效。
240
+ - 类型: `boolean`
241
+ - 默认值: `false`
242
+ - `outDirName`: 输出的目录名称,只在生产环境下生效。
243
+ - 类型: `string`
244
+ - 默认值: `"dist"`
245
+ - `outReport`: 是否输出打包分析报告,只在生产环境下生效。
246
+ - 类型: `boolean`
247
+ - 默认值: `false`
248
+ - `cache`: 是否缓存编译结果。
249
+ - 类型: `boolean`
250
+ - 默认值: `false`
251
+
252
+ ## resolve
253
+
254
+ resolve 配置。
255
+
256
+ - 类型: `object`
257
+ - `alias`: 路径别名。
258
+ - 类型: `Record<string, string>`
259
+ - 默认值: `{'@': path.join(context,'src')}`
260
+ - 参考: [Resolve Alias](https://webpack.js.org/configuration/resolve/#resolvealias)
261
+ - `extensions`: 默认后缀。
262
+ - 类型: `string[]`
263
+ - 默认值: [".js", ".json", ".wasm",'.mjs', '.jsx', '.ts', '.tsx']
264
+ - 参考: [Resolve Extensions](https://webpack.js.org/configuration/resolve/#resolveextensions)
265
+
266
+ ## 辅助工具函数
267
+
268
+ ### defineConfig
269
+
270
+ 定义配置的辅助工具函数。
271
+
272
+ - 类型: `(config: UserConfigWebExport) => UserConfigWebExport`
package/dist/cli.js DELETED
@@ -1,371 +0,0 @@
1
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
- }) : x)(function(x) {
4
- if (typeof require !== "undefined")
5
- return require.apply(this, arguments);
6
- throw Error('Dynamic require of "' + x + '" is not supported');
7
- });
8
-
9
- // src/node/cli.ts
10
- import { cac } from "cac";
11
-
12
- // package.json
13
- var name = "@ikaros-cli/ikaros-cli";
14
- var version = "1.0.0";
15
-
16
- // src/node/utils/tools.ts
17
- import chalk from "chalk";
18
- var cliPackageJson = { version, name };
19
- var rootDir = process.cwd();
20
-
21
- // src/node/utils/build-rollup-config.ts
22
- import { nodeResolve } from "@rollup/plugin-node-resolve";
23
- import commonjs from "@rollup/plugin-commonjs";
24
- import json from "@rollup/plugin-json";
25
- import esbuild from "rollup-plugin-esbuild";
26
- import obfuscator from "rollup-plugin-obfuscator";
27
-
28
- // src/node/utils/build-vite-config.ts
29
- import { join } from "node:path";
30
-
31
- // src/node/plugins/vite-plugin/external-builtins.ts
32
- import { builtinModules } from "node:module";
33
- var externalBuiltins = () => {
34
- return {
35
- name: "@ikaros-cli/external-builtins",
36
- config(config) {
37
- const nativeModules = builtinModules.filter((e) => !e.startsWith("_"));
38
- const builtins = [
39
- "electron",
40
- ...nativeModules,
41
- ...nativeModules.map((m) => `node:${m}`)
42
- ];
43
- config.build ??= {};
44
- config.build.rollupOptions ??= {};
45
- let external = config.build.rollupOptions.external;
46
- if (Array.isArray(external) || typeof external === "string" || external instanceof RegExp) {
47
- external = builtins.concat(external);
48
- } else if (typeof external === "function") {
49
- const original = external;
50
- external = function(source, importer, isResolved) {
51
- if (builtins.includes(source)) {
52
- return true;
53
- }
54
- return original(source, importer, isResolved);
55
- };
56
- } else {
57
- external = builtins;
58
- }
59
- config.build.rollupOptions.external = external;
60
- }
61
- };
62
- };
63
-
64
- // src/node/utils/build-vite-config.ts
65
- var getUserConfig = (config) => {
66
- const {
67
- renderer,
68
- entryDir,
69
- outputDir,
70
- target,
71
- mode
72
- } = config;
73
- const { viteOption } = renderer ?? {};
74
- const root = join(rootDir, entryDir);
75
- const outDir = join(rootDir, outputDir);
76
- const defineConfig = {
77
- base: "./",
78
- root,
79
- build: {
80
- reportCompressedSize: false,
81
- outDir
82
- }
83
- };
84
- const viteConfig = Object.assign({}, viteOption, defineConfig);
85
- return {
86
- mode,
87
- target,
88
- entryDir,
89
- outputDir,
90
- viteOption: viteConfig
91
- };
92
- };
93
- var buildViteConfig = (userConfig) => {
94
- const { viteOption, mode, target } = getUserConfig(userConfig);
95
- const plugins = viteOption.plugins || [];
96
- if (mode !== "web") {
97
- plugins.push(externalBuiltins());
98
- }
99
- if (target === "mobile" && mode === "web") {
100
- }
101
- viteOption.plugins = plugins;
102
- return viteOption;
103
- };
104
-
105
- // src/node/utils/load-config.ts
106
- import { dirname, extname, isAbsolute, join as join2, resolve } from "node:path";
107
- import { pathToFileURL } from "node:url";
108
- import { createRequire } from "node:module";
109
- import { parse } from "yaml";
110
- import fs from "fs";
111
- import fsp from "node:fs/promises";
112
- import fse from "fs-extra";
113
- import { build } from "esbuild";
114
- async function transformConfig(input, isESM = false) {
115
- const result = await build({
116
- absWorkingDir: process.cwd(),
117
- entryPoints: [input],
118
- outfile: "out.js",
119
- write: false,
120
- platform: "node",
121
- bundle: true,
122
- format: isESM ? "esm" : "cjs",
123
- sourcemap: "inline",
124
- metafile: true,
125
- plugins: [
126
- // 对裸模块,进行 external 处理,即不打包到 bundle
127
- {
128
- name: "externalize-deps",
129
- setup(build2) {
130
- build2.onResolve({ filter: /.*/ }, (args) => {
131
- const id = args.path;
132
- if (!id.startsWith(".") && !isAbsolute(id)) {
133
- return {
134
- external: true
135
- };
136
- }
137
- });
138
- }
139
- }
140
- // 省略其他插件
141
- ]
142
- });
143
- const { text } = result.outputFiles[0];
144
- return {
145
- code: text,
146
- dependencies: result.metafile ? Object.keys(result.metafile.inputs) : []
147
- };
148
- }
149
- var _require = createRequire(pathToFileURL(resolve()));
150
- async function requireConfig(fileName, code, isESM = false) {
151
- if (isESM) {
152
- const fileBase = `${fileName}.timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
153
- const fileNameTmp = `${fileBase}.mjs`;
154
- const fileUrl = `${pathToFileURL(fileBase)}.mjs`;
155
- await fsp.writeFile(fileNameTmp, code);
156
- try {
157
- return (await import(fileUrl)).default;
158
- } finally {
159
- fs.unlink(fileNameTmp, () => {
160
- });
161
- }
162
- }
163
- const extension = extname(fileName);
164
- const realFileName = fs.realpathSync(fileName);
165
- const loaderExt = extension in _require.extensions ? extension : ".js";
166
- const defaultLoader = _require.extensions[loaderExt];
167
- _require.extensions[loaderExt] = (module, filename) => {
168
- if (filename === realFileName) {
169
- ;
170
- module._compile(code, filename);
171
- } else {
172
- defaultLoader(module, filename);
173
- }
174
- };
175
- delete __require.cache[__require.resolve(fileName)];
176
- const raw = _require(fileName);
177
- _require.extensions[loaderExt] = defaultLoader;
178
- return raw.__esModule ? raw.default : raw;
179
- }
180
- async function resultConfig(filePath, isESM = false) {
181
- const { code } = await transformConfig(filePath, isESM);
182
- return requireConfig(filePath, code, isESM);
183
- }
184
- var fileType = /* @__PURE__ */ new Map();
185
- fileType.set(".mjs", async (filePath) => {
186
- const fileUrl = pathToFileURL(filePath);
187
- return (await import(fileUrl.href)).default;
188
- });
189
- fileType.set(".ts", async (filePath) => {
190
- return await resultConfig(filePath, true);
191
- });
192
- fileType.set(".json", async (filePath) => {
193
- return await fse.readJson(filePath);
194
- });
195
- fileType.set(".yaml", async (filePath) => {
196
- const text = await fsp.readFile(filePath, "utf8");
197
- return parse(text);
198
- });
199
- async function resolveConfig({
200
- configFile
201
- }) {
202
- let suffix;
203
- let configPath = process.cwd();
204
- let configName = "ikaros-cli.config";
205
- const configList = ["ts", "mjs", "json", "yaml"].map(
206
- (suffix2) => `${join2(configPath, configName)}.${suffix2}`
207
- );
208
- const index = (await Promise.all(configList.map((element) => {
209
- return fse.pathExists(element);
210
- }))).findIndex(Boolean);
211
- if (index < 0)
212
- return void 0;
213
- suffix = extname(configList[index]);
214
- configPath = resolve(configPath, `${configName}${suffix}`);
215
- if (configFile) {
216
- configPath = dirname(configFile);
217
- suffix = extname(configFile);
218
- }
219
- if (!fileType.has(suffix))
220
- throw new Error("No configuration file ! ");
221
- return fileType.get(suffix)(configPath);
222
- }
223
-
224
- // src/node/utils/get-config.ts
225
- var getConfig = async (configFile) => {
226
- const config = {
227
- mode: "web",
228
- target: "web",
229
- entryDir: "src",
230
- outputDir: "dist",
231
- main: {},
232
- renderer: {}
233
- };
234
- let fileConfig = void 0;
235
- fileConfig = await resolveConfig({ configFile });
236
- if (fileConfig) {
237
- return fileConfig;
238
- }
239
- return config;
240
- };
241
-
242
- // src/node/utils/logger.ts
243
- import readline from "node:readline";
244
- import colors from "picocolors";
245
- var LogLevels = {
246
- silent: 0,
247
- error: 1,
248
- warn: 2,
249
- info: 3
250
- };
251
- var lastType;
252
- var lastMsg;
253
- var sameCount = 0;
254
- function clearScreen() {
255
- const repeatCount = process.stdout.rows - 2;
256
- const blank = repeatCount > 0 ? "\n".repeat(repeatCount) : "";
257
- console.log(blank);
258
- readline.cursorTo(process.stdout, 0, 0);
259
- readline.clearScreenDown(process.stdout);
260
- }
261
- function createLogger(level = "info", options = {}) {
262
- if (options.customLogger) {
263
- return options.customLogger;
264
- }
265
- const loggedErrors = /* @__PURE__ */ new WeakSet();
266
- const {
267
- prefix = "[ikaros-cli]",
268
- allowClearScreen = true,
269
- timestamp = true,
270
- error
271
- } = options;
272
- const thresh = LogLevels[level];
273
- const canClearScreen = allowClearScreen && process.stdout.isTTY && !process.env.CI;
274
- const clear = canClearScreen ? clearScreen : () => {
275
- };
276
- function output(type, msg, options2 = {}) {
277
- if (thresh >= LogLevels[type]) {
278
- const method = type === "info" ? "log" : type;
279
- const format = () => {
280
- if (timestamp) {
281
- const tag = type === "info" ? colors.cyan(colors.bold(prefix)) : type === "warn" ? colors.yellow(colors.bold(prefix)) : colors.red(colors.bold(prefix));
282
- return `${colors.dim((/* @__PURE__ */ new Date()).toLocaleTimeString())} ${tag} ${msg}`;
283
- } else {
284
- return msg;
285
- }
286
- };
287
- if (error) {
288
- loggedErrors.add(error);
289
- }
290
- if (canClearScreen) {
291
- if (type === lastType && msg === lastMsg) {
292
- sameCount++;
293
- clear();
294
- console[method](format(), colors.yellow(`(x${sameCount + 1})`));
295
- } else {
296
- sameCount = 0;
297
- lastMsg = msg;
298
- lastType = type;
299
- if (options2.clear) {
300
- clear();
301
- }
302
- console[method](format());
303
- }
304
- } else {
305
- console[method](format());
306
- }
307
- }
308
- }
309
- const warnedMessages = /* @__PURE__ */ new Set();
310
- const logger2 = {
311
- hasWarned: false,
312
- info(msg, opts) {
313
- output("info", msg, opts);
314
- },
315
- warn(msg, opts) {
316
- logger2.hasWarned = true;
317
- output("warn", msg, opts);
318
- },
319
- warnOnce(msg, opts) {
320
- if (warnedMessages.has(msg))
321
- return;
322
- logger2.hasWarned = true;
323
- output("warn", msg, opts);
324
- warnedMessages.add(msg);
325
- },
326
- error(msg, opts) {
327
- logger2.hasWarned = true;
328
- output("error", msg, opts);
329
- },
330
- clearScreen(type) {
331
- if (thresh >= LogLevels[type]) {
332
- clear();
333
- }
334
- },
335
- hasErrorLogged(error2) {
336
- return loggedErrors.has(error2);
337
- }
338
- };
339
- return logger2;
340
- }
341
-
342
- // src/node/runner/dev-runner.ts
343
- import { createServer } from "vite";
344
- var logger = createLogger("info", { prefix: "ikaros-cli:runner" });
345
- var devRunner = async (fileName) => {
346
- const config = await getConfig(fileName);
347
- const { mode, target } = config;
348
- logger.info(`mode: ${mode}, target: ${target}`);
349
- const viteConfig = buildViteConfig(config);
350
- if (mode === "web") {
351
- const server = await createServer({ configFile: false, ...viteConfig });
352
- await server.listen();
353
- server.printUrls();
354
- server.bindCLIShortcuts({ print: true });
355
- return;
356
- }
357
- };
358
-
359
- // src/node/cli.ts
360
- var cli = cac("ikaros");
361
- cli.option("-m , --mode <mode>", "[dev | prod | test | sit | ...] \u73AF\u5883\u6A21\u5F0F ").option("dev, server", "\u5F00\u53D1\u73AF\u5883\u542F\u52A8,\u5141\u8BB8\u8854\u63A5m[mode]\u53C2\u6570\u6765\u63A7\u5236\u5F53\u524D\u73AF\u5883").option("build", "\u6253\u5305\u6A21\u5F0F\uFF0C");
362
- cli.command("[config-file]", "start dev server").alias("dev").alias("server").action(async (configFile, options) => {
363
- devRunner(configFile);
364
- });
365
- cli.command("build [root]", "build app with mode").alias("build").action(async (options) => {
366
- console.log("build mode", options);
367
- });
368
- cli.help();
369
- cli.version(cliPackageJson.version);
370
- cli.parse();
371
- //# sourceMappingURL=cli.js.map
package/dist/cli.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/node/cli.ts","../package.json","../src/node/utils/tools.ts","../src/node/utils/build-rollup-config.ts","../src/node/utils/build-vite-config.ts","../src/node/plugins/vite-plugin/external-builtins.ts","../src/node/utils/load-config.ts","../src/node/utils/get-config.ts","../src/node/utils/logger.ts","../src/node/runner/dev-runner.ts"],"sourcesContent":["import { cac } from 'cac'\nimport { cliPackageJson } from './utils/tools'\nimport { devRunner } from './runner/dev-runner'\n\nconst cli = cac('ikaros')\n\ncli\n .option('-m , --mode <mode>', '[dev | prod | test | sit | ...] 环境模式 ')\n .option('dev, server', '开发环境启动,允许衔接m[mode]参数来控制当前环境')\n .option('build', '打包模式,')\n\ninterface GlobalCLIOptions {\n '--': string[]\n m: string\n mode: string\n}\n\ncli\n .command('[config-file]', 'start dev server')\n .alias('dev')\n .alias('server')\n .action(async (configFile: undefined | string, options: GlobalCLIOptions) => {\n devRunner(configFile)\n })\n\ncli\n .command('build [root]', 'build app with mode')\n .alias('build')\n .action(async (options: GlobalCLIOptions) => {\n console.log('build mode', options)\n })\n\ncli.help()\ncli.version(cliPackageJson.version)\ncli.parse()","{\n \"name\": \"@ikaros-cli/ikaros-cli\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"type\": \"module\",\n \"scripts\": {\n \"dev\": \"tsup --watch\",\n \"dts\": \"tsup --dts\",\n \"build\": \"tsup\"\n },\n \"keywords\": [\n \"electron\",\n \"vue\",\n \"vite\"\n ],\n \"author\": \"sky <https://github.com/umbrella22>\",\n \"license\": \"MIT\",\n \"main\": \"dist/cli.js\",\n \"module\": \"dist/cli.js\",\n \"types\": \"dist/index.d.ts\",\n \"bin\": {\n \"ikaros-cli\": \"dist/cli.js\"\n },\n \"files\": [\n \"dist\"\n ],\n \"peerDependencies\": {\n \"electron\": \">=29.0.0\"\n },\n \"engines\": {\n \"node\": \">=18.0.0\",\n \"npm\": \">=9.5.0\"\n },\n \"dependencies\": {\n \"@rollup/plugin-alias\": \"^5.1.0\",\n \"@rollup/plugin-commonjs\": \"^25.0.7\",\n \"@rollup/plugin-json\": \"^6.1.0\",\n \"@rollup/plugin-node-resolve\": \"^15.2.3\",\n \"@rollup/plugin-replace\": \"^5.0.5\",\n \"cac\": \"^6.7.14\",\n \"chalk\": \"^5.3.0\",\n \"dotenv\": \"^16.4.5\",\n \"electron-builder\": \"^23.6.0\",\n \"esbuild\": \"^0.19.12\",\n \"fs-extra\": \"^11.2.0\",\n \"glob\": \"^10.3.15\",\n \"inquirer\": \"^9.2.22\",\n \"javascript-obfuscator\": \"^4.1.0\",\n \"picocolors\": \"^1.0.1\",\n \"portfinder\": \"^1.0.32\",\n \"postcss-px-to-viewport-8-plugin\": \"^1.2.5\",\n \"rollup\": \"^4.17.2\",\n \"rollup-plugin-esbuild\": \"^6.1.1\",\n \"rollup-plugin-obfuscator\": \"^1.1.0\",\n \"vite\": \"^5.2.11\",\n \"yaml\": \"^2.4.2\"\n },\n \"devDependencies\": {\n \"@types/fs-extra\": \"^11.0.4\"\n }\n}","import { version, name } from '../../../package.json'\nimport chalk from \"chalk\"\n\n/**\n * cli package.json\n */\nexport const cliPackageJson = { version, name }\n\nexport const rootDir = process.cwd()\n\nexport function logStats(proc: string, data: any) {\n let log = \"\";\n\n log += chalk.yellow.bold(\n `┏ ${proc} \"Process\" ${new Array(\n 19 - proc.length + 1\n ).join(\"-\")}`\n );\n log += \"\\n\\n\";\n\n if (typeof data === \"object\") {\n data\n .toString({\n colors: true,\n chunks: false,\n })\n .split(/\\r?\\n/)\n .forEach((line: string) => {\n log += \" \" + line + \"\\n\";\n });\n } else {\n log += ` ${data}\\n`;\n }\n\n log += \"\\n\" + chalk.yellow.bold(`┗ ${new Array(28 + 1).join(\"-\")}`) + \"\\n\";\n console.log(log);\n}\n\nexport function removeJunk(chunk: string) {\n // Example: 2018-08-10 22:48:42.866 Electron[90311:4883863] *** WARNING: Textured window <AtomNSWindow: 0x7fb75f68a770>\n if (\n /\\d+-\\d+-\\d+ \\d+:\\d+:\\d+\\.\\d+ Electron(?: Helper)?\\[\\d+:\\d+] /.test(chunk)\n ) {\n return false;\n }\n\n // Example: [90789:0810/225804.894349:ERROR:CONSOLE(105)] \"Uncaught (in promise) Error: Could not instantiate: ProductRegistryImpl.Registry\", source: chrome-devtools://devtools/bundled/inspector.js (105)\n if (/\\[\\d+:\\d+\\/|\\d+\\.\\d+:ERROR:CONSOLE\\(\\d+\\)\\]/.test(chunk)) {\n return false;\n }\n\n // Example: ALSA lib confmisc.c:767:(parse_card) cannot find card '0'\n if (/ALSA lib [a-z]+\\.c:\\d+:\\([a-z_]+\\)/.test(chunk)) {\n return false;\n }\n return chunk;\n}\n\n","import { nodeResolve } from '@rollup/plugin-node-resolve'\nimport { builtinModules } from 'node:module'\nimport commonjs from '@rollup/plugin-commonjs'\nimport json from '@rollup/plugin-json'\nimport esbuild, { type Options } from 'rollup-plugin-esbuild'\nimport obfuscator from 'rollup-plugin-obfuscator'\nimport type { RollupOptions } from 'rollup'\nimport type { IkarosUserConfig } from '../user-config'\nimport { rootDir } from './tools'\nimport { join } from 'node:path'\n\ninterface RollupExOptions {\n inputFile: string\n outputFile: string\n}\n\n/**\n * Build rollup config\n */\nconst getRollupConfig = (\n config: IkarosUserConfig,\n options?: RollupExOptions,\n) => {\n const {\n main,\n entryDir,\n outputDir,\n } = config\n const {\n rollupOption,\n obfuscate,\n obfuscateOptions,\n esbuildOption,\n } = main ?? {}\n if (!options) {\n options = {\n inputFile: 'index.js',\n outputFile: 'main.js',\n }\n }\n const { inputFile, outputFile } = options\n const input = join(rootDir, entryDir, inputFile)\n const output = join(rootDir, outputDir, outputFile)\n const defineConfig: RollupOptions = {\n input,\n output: {\n file: output,\n format: 'cjs',\n exports: 'auto',\n sourcemap: false,\n },\n }\n const rollupConfig = Object.assign({}, rollupOption, defineConfig)\n\n return {\n obfuscate,\n entryDir,\n outputDir,\n rollupConfig,\n obfuscateOptions,\n esbuildOption,\n }\n}\n\nexport const buildRollupConfig = (\n userConfig: IkarosUserConfig,\n options?: RollupExOptions,\n): RollupOptions => {\n const { rollupConfig, obfuscate, obfuscateOptions, esbuildOption } =\n getRollupConfig(userConfig, options)\n const { external, plugins } = rollupConfig\n const exExternal = external || []\n const exPlugins = plugins || []\n\n const defaultEsbuildOption: Options = {\n include: /\\.[jt]s?$/,\n exclude: /node_modules/,\n target: 'esnext',\n // Add extra loaders\n loaders: {\n '.json': 'json',\n '.js': 'jsx',\n },\n }\n\n if (Array.isArray(exExternal)) {\n exExternal.push(...builtinModules)\n }\n\n if (Array.isArray(exPlugins)) {\n exPlugins.push(\n commonjs(),\n json(),\n nodeResolve(),\n esbuild(esbuildOption ?? defaultEsbuildOption),\n )\n if (obfuscate) {\n exPlugins.push(obfuscator(obfuscateOptions ?? {\n global: true,\n }))\n }\n }\n\n rollupConfig.plugins = exPlugins\n rollupConfig.external = exExternal\n\n return rollupConfig\n}\n","import { join } from 'node:path'\nimport type { UserConfig } from 'vite'\nimport type { IkarosUserConfig } from '../user-config'\nimport { rootDir } from './tools'\nimport { externalBuiltins } from '../plugins/vite-plugin/external-builtins'\nimport { } from \"../plugins/vite-plugin/fix-name-lose\"\n\nconst getUserConfig = (config: IkarosUserConfig) => {\n const {\n renderer,\n entryDir,\n outputDir,\n target,\n mode,\n } = config\n const { viteOption } = renderer ?? {}\n const root = join(rootDir, entryDir)\n const outDir = join(rootDir, outputDir)\n const defineConfig: UserConfig = {\n base: './',\n root,\n build: {\n reportCompressedSize: false,\n outDir,\n },\n }\n const viteConfig = Object.assign({}, viteOption, defineConfig)\n return {\n mode,\n target,\n entryDir,\n outputDir,\n viteOption: viteConfig,\n }\n}\n\nexport const buildViteConfig = (userConfig: IkarosUserConfig): UserConfig => {\n const { viteOption, mode, target } = getUserConfig(userConfig)\n\n const plugins = viteOption.plugins || []\n\n if (mode !== 'web') {\n plugins.push(externalBuiltins(),)\n }\n if (target === 'mobile' && mode === 'web') {\n // TODO 记得添加移动端插件\n\n }\n\n\n viteOption.plugins = plugins\n\n return viteOption\n}\n","import { builtinModules } from 'node:module'\n\nimport type { Plugin } from 'vite'\n\n/**\n * `electron` and Node.js built-in modules should always be externalize.\n */\nexport const externalBuiltins = () => {\n return <Plugin>{\n name: '@ikaros-cli/external-builtins',\n config(config) {\n const nativeModules = builtinModules.filter((e) => !e.startsWith('_'))\n const builtins = [\n 'electron',\n ...nativeModules,\n ...nativeModules.map((m) => `node:${m}`),\n ]\n\n config.build ??= {}\n config.build.rollupOptions ??= {}\n\n let external = config.build.rollupOptions.external\n if (\n Array.isArray(external) ||\n typeof external === 'string' ||\n external instanceof RegExp\n ) {\n external = builtins.concat(external as string[])\n } else if (typeof external === 'function') {\n const original = external\n external = function (source, importer, isResolved) {\n if (builtins.includes(source)) {\n return true\n }\n return original(source, importer, isResolved)\n }\n } else {\n external = builtins\n }\n config.build.rollupOptions.external = external\n },\n }\n}\n","import { dirname, extname, isAbsolute, join, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { createRequire } from 'node:module'\nimport { parse } from 'yaml'\nimport fs from 'fs'\nimport fsp from 'node:fs/promises'\nimport fse from 'fs-extra'\nimport { build } from 'esbuild'\nimport type { IkarosUserConfig } from '../user-config.ts'\n\nasync function transformConfig(input: string, isESM = false) {\n const result = await build({\n absWorkingDir: process.cwd(),\n entryPoints: [input],\n outfile: 'out.js',\n write: false,\n platform: 'node',\n bundle: true,\n format: isESM ? 'esm' : 'cjs',\n sourcemap: 'inline',\n metafile: true,\n plugins: [\n // 对裸模块,进行 external 处理,即不打包到 bundle\n {\n name: 'externalize-deps',\n setup(build) {\n build.onResolve({ filter: /.*/ }, (args) => {\n const id = args.path\n // 排除相对路径和绝对路径\n if (!id.startsWith('.') && !isAbsolute(id)) {\n return {\n external: true,\n }\n }\n })\n },\n },\n // 省略其他插件\n ],\n })\n\n const { text } = result.outputFiles[0]\n return {\n code: text,\n dependencies: result.metafile ? Object.keys(result.metafile.inputs) : [],\n }\n}\n\ninterface NodeModuleWithCompile extends NodeModule {\n _compile(code: string, filename: string): any\n}\nconst _require = createRequire(pathToFileURL(resolve()))\nasync function requireConfig(fileName: string, code: string, isESM = false) {\n\n if (isESM) {\n const fileBase = `${fileName}.timestamp-${Date.now()}-${Math.random()\n .toString(16)\n .slice(2)}`\n const fileNameTmp = `${fileBase}.mjs`\n const fileUrl = `${pathToFileURL(fileBase)}.mjs`\n await fsp.writeFile(fileNameTmp, code)\n try {\n return (await import(fileUrl)).default\n } finally {\n fs.unlink(fileNameTmp, () => { }) // Ignore errors\n }\n }\n\n const extension = extname(fileName)\n const realFileName = fs.realpathSync(fileName)\n const loaderExt = extension in _require.extensions ? extension : '.js'\n\n // 保存老的 require 行为\n const defaultLoader = _require.extensions[loaderExt]!\n // 临时重写当前配置文件后缀的 require 行为\n _require.extensions[loaderExt] = (module: NodeModule, filename: string) => {\n // 只处理配置文件\n if (filename === realFileName) {\n // 直接调用 compile,传入编译好的代码\n ; (module as NodeModuleWithCompile)._compile(code, filename)\n } else {\n defaultLoader(module, filename)\n }\n }\n // 清除缓存\n // eslint-disable-next-line unicorn/prefer-module\n delete require.cache[require.resolve(fileName)]\n const raw = _require(fileName)\n // 恢复原生require行为\n _require.extensions[loaderExt] = defaultLoader\n // 如果是esm编译过的__esModule为true\n return raw.__esModule ? raw.default : raw\n}\n\nasync function resultConfig(filePath: string, isESM = false) {\n const { code } = await transformConfig(filePath, isESM)\n return requireConfig(filePath, code, isESM)\n}\n\n\ntype FileType = '.mjs' | '.ts' | '.json' | '.yaml'\n\nconst fileType = new Map<FileType, (filePath: string) => Promise<any>>()\n\n// fileType.set('.js', async (filePath) => {\n// const pkg = await fse.readJson(resolve(process.cwd(), 'package.json'))\n// const { type = 'commonjs' } = pkg\n// return new Promise((resolve) => {\n// if (type === 'module') {\n// const fileUrl = pathToFileURL(filePath)\n// import(fileUrl.href)\n// .then((config) => config?.default)\n// .then(resolve)\n// }\n\n// // commonjs\n// resultConfig(filePath).then(resolve)\n// })\n// })\n\nfileType.set('.mjs', async (filePath) => {\n const fileUrl = pathToFileURL(filePath)\n return (await import(fileUrl.href)).default\n})\n\nfileType.set('.ts', async (filePath) => {\n return await resultConfig(filePath, true)\n})\n\n\nfileType.set('.json', async (filePath) => {\n return await fse.readJson(filePath)\n})\n\nfileType.set('.yaml', async (filePath) => {\n const text = await fsp.readFile(filePath, 'utf8')\n return parse(text)\n})\n\n/**\n * @description 解析配置文件\n * @date 2024-05-22\n * @param {string} configFile 文件路径,可选,若不传入则会在项目根目录寻找配置文件\n * @returns {Promise<IkarosUserConfig | undefined>}\n */\nexport async function resolveConfig({\n configFile\n}: {\n configFile?: string\n}): Promise<IkarosUserConfig | undefined> {\n let suffix: FileType | undefined\n let configPath = process.cwd()\n let configName = 'ikaros-cli.config'\n\n const configList = ['ts', 'mjs', 'json', 'yaml'].map(\n (suffix) => `${join(configPath, configName)}.${suffix}`,\n )\n const index = (\n await Promise.all(configList.map((element) => {\n return fse.pathExists(element)\n }))\n ).findIndex(Boolean)\n if (index < 0) return undefined\n\n suffix = extname(configList[index]) as FileType\n\n configPath = resolve(configPath, `${configName}${suffix}`)\n\n if (configFile) {\n configPath = dirname(configFile)\n suffix = extname(configFile) as FileType\n }\n\n if (!fileType.has(suffix)) throw new Error('No configuration file ! ')\n return fileType.get(suffix)!(configPath)\n}\n","import type { IkarosUserConfig } from \"..\"\nimport { resolveConfig } from \"./load-config\"\n\nexport const getConfig = async (configFile?: string): Promise<IkarosUserConfig> => {\n const config: IkarosUserConfig = {\n mode: 'web',\n target: 'web',\n entryDir: 'src',\n outputDir: 'dist',\n main: {},\n renderer: {}\n }\n let fileConfig: IkarosUserConfig | undefined = undefined\n\n fileConfig = await resolveConfig({ configFile });\n if (fileConfig) {\n return fileConfig\n }\n return config;\n}","/* eslint no-console: 0 */\n\nimport readline from 'node:readline'\nimport colors from 'picocolors'\nimport type { RollupError } from 'rollup'\n\nexport type LogType = 'error' | 'warn' | 'info'\nexport type LogLevel = LogType | 'silent'\nexport interface Logger {\n info(msg: string, options?: LogOptions): void\n warn(msg: string, options?: LogOptions): void\n warnOnce(msg: string, options?: LogOptions): void\n error(msg: string, options?: LogErrorOptions): void\n clearScreen(type: LogType): void\n hasErrorLogged(error: Error | RollupError): boolean\n hasWarned: boolean\n}\n\nexport interface LogOptions {\n clear?: boolean\n timestamp?: boolean\n}\n\nexport interface LogErrorOptions extends LogOptions {\n error?: Error | RollupError | null\n}\n\nexport const LogLevels: Record<LogLevel, number> = {\n silent: 0,\n error: 1,\n warn: 2,\n info: 3,\n}\n\nlet lastType: LogType | undefined\nlet lastMsg: string | undefined\nlet sameCount = 0\n\nfunction clearScreen() {\n const repeatCount = process.stdout.rows - 2\n const blank = repeatCount > 0 ? '\\n'.repeat(repeatCount) : ''\n console.log(blank)\n readline.cursorTo(process.stdout, 0, 0)\n readline.clearScreenDown(process.stdout)\n}\n\nexport interface LoggerOptions {\n prefix?: string\n allowClearScreen?: boolean\n customLogger?: Logger\n timestamp?: string\n error?: Error | RollupError\n}\n\nexport function createLogger(\n level: LogLevel = 'info',\n options: LoggerOptions = {},\n): Logger {\n if (options.customLogger) {\n return options.customLogger\n }\n\n const loggedErrors = new WeakSet<Error | RollupError>()\n const {\n prefix = '[ikaros-cli]',\n allowClearScreen = true,\n timestamp = true,\n error,\n } = options\n const thresh = LogLevels[level]\n const canClearScreen =\n allowClearScreen && process.stdout.isTTY && !process.env.CI\n const clear = canClearScreen ? clearScreen : () => { }\n\n function output(type: LogType, msg: string, options: LogErrorOptions = {}) {\n if (thresh >= LogLevels[type]) {\n const method = type === 'info' ? 'log' : type\n const format = () => {\n if (timestamp) {\n const tag =\n type === 'info'\n ? colors.cyan(colors.bold(prefix))\n : type === 'warn'\n ? colors.yellow(colors.bold(prefix))\n : colors.red(colors.bold(prefix))\n return `${colors.dim(new Date().toLocaleTimeString())} ${tag} ${msg}`\n } else {\n return msg\n }\n }\n if (error) {\n loggedErrors.add(error)\n }\n if (canClearScreen) {\n if (type === lastType && msg === lastMsg) {\n sameCount++\n clear()\n console[method](format(), colors.yellow(`(x${sameCount + 1})`))\n } else {\n sameCount = 0\n lastMsg = msg\n lastType = type\n if (options.clear) {\n clear()\n }\n console[method](format())\n }\n } else {\n console[method](format())\n }\n }\n }\n\n const warnedMessages = new Set<string>()\n\n const logger: Logger = {\n hasWarned: false,\n info(msg, opts) {\n output('info', msg, opts)\n },\n warn(msg, opts) {\n logger.hasWarned = true\n output('warn', msg, opts)\n },\n warnOnce(msg, opts) {\n if (warnedMessages.has(msg)) return\n logger.hasWarned = true\n output('warn', msg, opts)\n warnedMessages.add(msg)\n },\n error(msg, opts) {\n logger.hasWarned = true\n output('error', msg, opts)\n },\n clearScreen(type) {\n if (thresh >= LogLevels[type]) {\n clear()\n }\n },\n hasErrorLogged(error) {\n return loggedErrors.has(error)\n },\n }\n\n return logger\n}\n","import { buildRollupConfig } from \"../utils/build-rollup-config\";\nimport { buildViteConfig } from \"../utils/build-vite-config\";\nimport { getConfig } from \"../utils/get-config\";\nimport { createLogger } from \"../utils/logger\";\nimport { createServer } from \"vite\"\n\n\nconst logger = createLogger('info', { prefix: 'ikaros-cli:runner' })\n\nexport const devRunner = async (fileName?: string): Promise<void> => {\n const config = await getConfig(fileName)\n const { mode, target } = config\n logger.info(`mode: ${mode}, target: ${target}`)\n const viteConfig = buildViteConfig(config)\n if (mode === 'web') {\n const server = await createServer({ configFile: false, ...viteConfig })\n await server.listen()\n server.printUrls()\n server.bindCLIShort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C3C,UAAQ,IAAI,cAAc,OAAO;AACnC,CAAC;AAEH,IAAI,KAAK;AACT,IAAI,QAAQ,eAAe,OAAO;AAClC,IAAI,MAAM;","names":["join","build","suffix","join","options","logger","error"]}
package/dist/index.js DELETED
@@ -1,13 +0,0 @@
1
- // src/node/user-config.ts
2
- var defineConfig = (config) => config;
3
-
4
- // package.json
5
- var version = "1.0.0";
6
-
7
- // src/node/index.ts
8
- var version2 = version;
9
- export {
10
- defineConfig,
11
- version2 as version
12
- };
13
- //# sourceMappingURL=index.js.map
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/node/user-config.ts","../package.json","../src/node/index.ts"],"sourcesContent":["import type { RollupOptions } from 'rollup'\nimport type { Options } from 'rollup-plugin-esbuild'\nimport type { RollupPluginObfuscatorOptions } from 'rollup-plugin-obfuscator'\nimport type { UserConfig } from 'vite'\n\ntype Preload =\n | {\n name: string\n entry: string\n }\n | string\nexport interface MainConfig {\n /** rollup配置 */\n rollupOption?: RollupOptions\n /** 是否混淆 */\n obfuscate?: boolean\n /** 是否生成字节码 */\n bytecode?: boolean\n /** 混淆配置 */\n obfuscateOptions?: RollupPluginObfuscatorOptions\n /** esbuild配置 */\n esbuildOption?: Options\n}\nexport interface RendererConfig {\n /** vite配置 */\n viteOption?: UserConfig\n}\nexport interface PreloadConfig extends MainConfig {\n /** 预加载脚本入口 */\n entry: Preload | Preload[]\n}\n\nexport interface BaseConfig {\n /** 模式:网页或者是客户端*/\n mode: 'web' | 'client'\n /** 标志:仅web模式生效 */\n target: 'web' | 'mobile'\n /** 入口目录 */\n entryDir: string\n /** 输出目录 */\n outputDir: string\n}\n\nexport interface IkarosUserConfig extends BaseConfig {\n /** 主进程配置 */\n main?: MainConfig\n /** 渲染进程配置 */\n renderer?: RendererConfig\n /** 预加载配置 */\n preload?: PreloadConfig\n}\nexport type ConfigEnv = {\n mode: BaseConfig['mode']\n target: BaseConfig['target']\n command: 'serve' | 'build'\n}\nexport type UserConfigFn = (env: ConfigEnv) => UserConfig | Promise<UserConfig>\n\n/** 辅助工具函数 */\nexport const defineConfig = (config: IkarosUserConfig) => config","{\n \"name\": \"@ikaros-cli/ikaros-cli\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"type\": \"module\",\n \"scripts\": {\n \"dev\": \"tsup --watch\",\n \"dts\": \"tsup --dts\",\n \"build\": \"tsup\"\n },\n \"keywords\": [\n \"electron\",\n \"vue\",\n \"vite\"\n ],\n \"author\": \"sky <https://github.com/umbrella22>\",\n \"license\": \"MIT\",\n \"main\": \"dist/cli.js\",\n \"module\": \"dist/cli.js\",\n \"types\": \"dist/index.d.ts\",\n \"bin\": {\n \"ikaros-cli\": \"dist/cli.js\"\n },\n \"files\": [\n \"dist\"\n ],\n \"peerDependencies\": {\n \"electron\": \">=29.0.0\"\n },\n \"engines\": {\n \"node\": \">=18.0.0\",\n \"npm\": \">=9.5.0\"\n },\n \"dependencies\": {\n \"@rollup/plugin-alias\": \"^5.1.0\",\n \"@rollup/plugin-commonjs\": \"^25.0.7\",\n \"@rollup/plugin-json\": \"^6.1.0\",\n \"@rollup/plugin-node-resolve\": \"^15.2.3\",\n \"@rollup/plugin-replace\": \"^5.0.5\",\n \"cac\": \"^6.7.14\",\n \"chalk\": \"^5.3.0\",\n \"dotenv\": \"^16.4.5\",\n \"electron-builder\": \"^23.6.0\",\n \"esbuild\": \"^0.19.12\",\n \"fs-extra\": \"^11.2.0\",\n \"glob\": \"^10.3.15\",\n \"inquirer\": \"^9.2.22\",\n \"javascript-obfuscator\": \"^4.1.0\",\n \"picocolors\": \"^1.0.1\",\n \"portfinder\": \"^1.0.32\",\n \"postcss-px-to-viewport-8-plugin\": \"^1.2.5\",\n \"rollup\": \"^4.17.2\",\n \"rollup-plugin-esbuild\": \"^6.1.1\",\n \"rollup-plugin-obfuscator\": \"^1.1.0\",\n \"vite\": \"^5.2.11\",\n \"yaml\": \"^2.4.2\"\n },\n \"devDependencies\": {\n \"@types/fs-extra\": \"^11.0.4\"\n }\n}","// 所有配置类型\nexport * from './user-config'\n\n// 虽然 ./utils.ts 也有导出,但为了节省标记树摇,这里做独立导出\nimport { version as _version } from '../../package.json'\n\n// 重命名导出\n/** 版本号 */\nexport const version = _version"],"mappings":";AA2DO,IAAM,eAAe,CAAC,WAA6B;;;ACzDxD,cAAW;;;ACMN,IAAMA,WAAU;","names":["version"]}