@nocobase/build 2.1.0-beta.9 → 2.2.0-alpha.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/lib/build.js CHANGED
@@ -28,12 +28,10 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
28
28
  var build_exports = {};
29
29
  __export(build_exports, {
30
30
  build: () => build,
31
- buildPackage: () => buildPackage,
32
31
  buildPackages: () => buildPackages
33
32
  });
34
33
  module.exports = __toCommonJS(build_exports);
35
34
  var import_chalk = __toESM(require("chalk"));
36
- var import_execa = __toESM(require("execa"));
37
35
  var import_path = __toESM(require("path"));
38
36
  var import_buildCjs = require("./buildCjs");
39
37
  var import_buildClient = require("./buildClient");
@@ -46,107 +44,313 @@ var import_utils = require("./utils");
46
44
  var import_addlicense = require("./utils/addlicense");
47
45
  var import_getPackages = require("./utils/getPackages");
48
46
  const BUILD_ERROR = "build-error";
47
+ const DEFAULT_LAYER_CONCURRENCY = 2;
48
+ const DEFAULT_PLUGIN_LAYER_CONCURRENCY = 1;
49
+ const ENABLE_BUILD_PROFILE = process.env.BUILD_PROFILE === "true";
49
50
  async function build(pkgs) {
51
+ const profile = ENABLE_BUILD_PROFILE ? (0, import_utils.createBuildProfileCollector)() : null;
52
+ const buildStart = (0, import_utils.nowMs)();
50
53
  const isDev = process.argv.includes("--development");
51
54
  process.env.NODE_ENV = isDev ? "development" : "production";
52
- let packages = (0, import_getPackages.getPackages)(pkgs);
53
- const cachePkg = (0, import_utils.readFromCache)(BUILD_ERROR);
54
- if (process.argv.includes("--retry") && cachePkg?.pkg) {
55
- packages = packages.slice(packages.findIndex((item) => item.name === cachePkg.pkg));
55
+ try {
56
+ let packages = (0, import_getPackages.getPackages)(pkgs);
57
+ const cachePkg = (0, import_utils.readFromCache)(BUILD_ERROR);
58
+ if (process.argv.includes("--retry") && cachePkg?.pkg) {
59
+ packages = packages.slice(packages.findIndex((item) => item.name === cachePkg.pkg));
60
+ }
61
+ const cliPackages = packages.find((item) => item.name === "@nocobase/cli");
62
+ if (cliPackages) {
63
+ const log = (0, import_utils.getPkgLog)(cliPackages.name);
64
+ log('running package script "build" (clean + tsc)');
65
+ await (0, import_utils.runScript)(["build"], cliPackages.location);
66
+ if (packages.length === 1) {
67
+ return;
68
+ }
69
+ }
70
+ if (packages.length === 0) {
71
+ let msg = "";
72
+ if (pkgs.length) {
73
+ msg = `'${pkgs.join(", ")}' did not match any packages`;
74
+ } else {
75
+ msg = "No package matched";
76
+ }
77
+ console.warn(import_chalk.default.yellow(`[@nocobase/build]: ${msg}`));
78
+ return;
79
+ }
80
+ const pluginPackages = (0, import_constant.getPluginPackages)(packages);
81
+ const cjsPackages = (0, import_constant.getCjsPackages)(packages);
82
+ const presetsPackages = (0, import_constant.getPresetsPackages)(packages);
83
+ await buildPackages(cjsPackages, "lib", import_buildCjs.buildCjs, {
84
+ sourceConcurrency: DEFAULT_LAYER_CONCURRENCY,
85
+ declarationConcurrency: 1,
86
+ stageName: "core cjs",
87
+ profile
88
+ });
89
+ const clientCore = packages.find((item) => item.location === import_constant.CORE_CLIENT);
90
+ const clientV2Core = packages.find((item) => item.location === import_constant.CORE_CLIENT_V2);
91
+ if (clientV2Core) {
92
+ await buildSinglePackage(clientV2Core, "es", import_buildClient.buildClient, {
93
+ stageName: "core client-v2",
94
+ profile
95
+ });
96
+ }
97
+ if (clientCore) {
98
+ await buildSinglePackage(clientCore, "es", import_buildClient.buildClient, {
99
+ stageName: "core client",
100
+ profile
101
+ });
102
+ }
103
+ const esmPackages = packages.filter((pkg) => import_constant.ESM_PACKAGES.includes(pkg.name));
104
+ await buildPackages(esmPackages, "lib", import_buildCjs.buildCjs, {
105
+ sourceConcurrency: DEFAULT_LAYER_CONCURRENCY,
106
+ declarationConcurrency: 1,
107
+ stageName: "esm cjs",
108
+ profile
109
+ });
110
+ await buildPackages(esmPackages, "es", import_buildEsm.buildEsm, {
111
+ sourceConcurrency: DEFAULT_LAYER_CONCURRENCY,
112
+ declarationConcurrency: 1,
113
+ stageName: "esm",
114
+ profile
115
+ });
116
+ await buildPackages(pluginPackages, "dist", import_buildPlugin.buildPlugin, {
117
+ sourceConcurrency: DEFAULT_PLUGIN_LAYER_CONCURRENCY,
118
+ declarationConcurrency: 1,
119
+ stageName: "plugins",
120
+ profile
121
+ });
122
+ await buildPackages(presetsPackages, "lib", import_buildCjs.buildCjs, {
123
+ sourceConcurrency: DEFAULT_LAYER_CONCURRENCY,
124
+ declarationConcurrency: 1,
125
+ stageName: "presets",
126
+ profile
127
+ });
128
+ const appClient = packages.find((item) => item.location === import_constant.CORE_APP);
129
+ if (appClient) {
130
+ await (0, import_utils.runProfiledStage)(profile, "app client shell", async () => {
131
+ await (0, import_utils.runScript)(["rsbuild", "build", "--config", import_path.default.join(import_constant.CORE_APP, "client", "rsbuild.config.ts")], import_constant.ROOT_PATH, {
132
+ APP_ROOT: import_path.default.join(import_constant.CORE_APP, "client"),
133
+ ANALYZE: process.env.BUILD_ANALYZE === "true" ? "1" : void 0
134
+ });
135
+ });
136
+ await (0, import_utils.runProfiledStage)(profile, "app client-v2 shell", async () => {
137
+ await (0, import_utils.runScript)(
138
+ ["rsbuild", "build", "--config", import_path.default.join(import_constant.CORE_APP, "client-v2", "rsbuild.config.ts")],
139
+ import_constant.ROOT_PATH,
140
+ {
141
+ ANALYZE: process.env.BUILD_ANALYZE === "true" ? "1" : void 0
142
+ }
143
+ );
144
+ });
145
+ }
146
+ (0, import_utils.writeToCache)(BUILD_ERROR, {});
147
+ } finally {
148
+ if (profile) {
149
+ (0, import_utils.printBuildProfile)(profile, (0, import_utils.nowMs)() - buildStart);
150
+ }
56
151
  }
57
- if (packages.length === 0) {
58
- let msg = "";
59
- if (pkgs.length) {
60
- msg = `'${pkgs.join(", ")}' did not match any packages`;
61
- } else {
62
- msg = "No package matched";
152
+ }
153
+ async function buildPackages(packages, targetDir, doBuildPackage, options = {}) {
154
+ const {
155
+ sourceConcurrency = DEFAULT_LAYER_CONCURRENCY,
156
+ declarationConcurrency = 1,
157
+ stageName = "packages",
158
+ profile = null
159
+ } = options;
160
+ const layers = (0, import_getPackages.groupPackagesByTopoLevel)(packages);
161
+ const shouldRunDeclaration = !process.argv.includes("--no-dts") && !process.argv.includes("--only-tar");
162
+ await (0, import_utils.runProfiledStage)(profile, `${stageName} source`, async () => {
163
+ for (let index = 0; index < layers.length; index++) {
164
+ const layer = layers[index];
165
+ console.log(import_chalk.default.cyan(`[@nocobase/build]: ${stageName} source layer ${index + 1}/${layers.length} (${layer.length} packages)`));
166
+ const layerStart = (0, import_utils.nowMs)();
167
+ await (0, import_utils.runWithConcurrency)(layer, sourceConcurrency, async (pkg) => {
168
+ await buildPackageSourceLifecycle(pkg, targetDir, doBuildPackage, profile);
169
+ });
170
+ const layerDurationMs = (0, import_utils.nowMs)() - layerStart;
171
+ if (profile) {
172
+ profile.layers.push({
173
+ stageName: `${stageName} source`,
174
+ layerIndex: index + 1,
175
+ layerCount: layers.length,
176
+ packageCount: layer.length,
177
+ durationMs: layerDurationMs
178
+ });
179
+ }
180
+ if (ENABLE_BUILD_PROFILE) {
181
+ console.log(import_chalk.default.gray(`[@nocobase/build]: ${stageName} source layer ${index + 1}/${layers.length} finished in ${(0, import_utils.formatDuration)(layerDurationMs)}`));
182
+ }
63
183
  }
64
- console.warn(import_chalk.default.yellow(`[@nocobase/build]: ${msg}`));
184
+ });
185
+ if (!shouldRunDeclaration) {
65
186
  return;
66
187
  }
67
- const pluginPackages = (0, import_constant.getPluginPackages)(packages);
68
- const cjsPackages = (0, import_constant.getCjsPackages)(packages);
69
- const presetsPackages = (0, import_constant.getPresetsPackages)(packages);
70
- await buildPackages(cjsPackages, "lib", import_buildCjs.buildCjs);
71
- const clientCore = packages.find((item) => item.location === import_constant.CORE_CLIENT);
72
- if (clientCore) {
73
- await buildPackage(clientCore, "es", import_buildClient.buildClient);
74
- }
75
- const esmPackages = packages.filter((pkg) => import_constant.ESM_PACKAGES.includes(pkg.name));
76
- await buildPackages(esmPackages, "lib", import_buildCjs.buildCjs);
77
- await buildPackages(esmPackages, "es", import_buildEsm.buildEsm);
78
- await buildPackages(pluginPackages, "dist", import_buildPlugin.buildPlugin);
79
- await buildPackages(presetsPackages, "lib", import_buildCjs.buildCjs);
80
- const appClient = packages.find((item) => item.location === import_constant.CORE_APP);
81
- if (appClient) {
82
- await runScript(["umi", "build"], import_constant.ROOT_PATH, {
83
- APP_ROOT: import_path.default.join(import_constant.CORE_APP, "client"),
84
- ANALYZE: process.env.BUILD_ANALYZE === "true" ? "1" : void 0
85
- });
86
- }
87
- (0, import_utils.writeToCache)(BUILD_ERROR, {});
188
+ await (0, import_utils.runProfiledStage)(profile, `${stageName} declaration`, async () => {
189
+ for (let index = 0; index < layers.length; index++) {
190
+ const layer = layers[index];
191
+ console.log(import_chalk.default.cyan(`[@nocobase/build]: ${stageName} declaration layer ${index + 1}/${layers.length} (${layer.length} packages)`));
192
+ const layerStart = (0, import_utils.nowMs)();
193
+ await (0, import_utils.runWithConcurrency)(layer, declarationConcurrency, async (pkg) => {
194
+ await buildPackageDeclarationLifecycle(pkg, targetDir, profile);
195
+ });
196
+ const layerDurationMs = (0, import_utils.nowMs)() - layerStart;
197
+ if (profile) {
198
+ profile.layers.push({
199
+ stageName: `${stageName} declaration`,
200
+ layerIndex: index + 1,
201
+ layerCount: layers.length,
202
+ packageCount: layer.length,
203
+ durationMs: layerDurationMs
204
+ });
205
+ }
206
+ if (ENABLE_BUILD_PROFILE) {
207
+ console.log(import_chalk.default.gray(`[@nocobase/build]: ${stageName} declaration layer ${index + 1}/${layers.length} finished in ${(0, import_utils.formatDuration)(layerDurationMs)}`));
208
+ }
209
+ }
210
+ });
88
211
  }
89
- async function buildPackages(packages, targetDir, doBuildPackage) {
90
- for await (const pkg of packages) {
91
- (0, import_utils.writeToCache)(BUILD_ERROR, { pkg: pkg.name });
92
- await buildPackage(pkg, targetDir, doBuildPackage);
212
+ async function buildSinglePackage(pkg, targetDir, doBuildPackage, options) {
213
+ const { stageName, profile = null } = options;
214
+ await (0, import_utils.runProfiledStage)(profile, `${stageName} source`, async () => {
215
+ await buildPackageSourceLifecycle(pkg, targetDir, doBuildPackage, profile);
216
+ });
217
+ if (process.argv.includes("--no-dts") || process.argv.includes("--only-tar")) {
218
+ return;
93
219
  }
220
+ await (0, import_utils.runProfiledStage)(profile, `${stageName} declaration`, async () => {
221
+ await buildPackageDeclarationLifecycle(pkg, targetDir, profile);
222
+ });
94
223
  }
95
- async function buildPackage(pkg, targetDir, doBuildPackage) {
224
+ async function buildPackageSourceLifecycle(pkg, targetDir, doBuildPackage, profile = null) {
96
225
  const sourcemap = process.argv.includes("--sourcemap");
97
- const noDeclaration = process.argv.includes("--no-dts");
98
226
  const hasTar = process.argv.includes("--tar");
99
227
  const onlyTar = process.argv.includes("--only-tar");
100
228
  const log = (0, import_utils.getPkgLog)(pkg.name);
101
229
  const packageJson = (0, import_utils.getPackageJson)(pkg.location);
102
230
  if (onlyTar) {
231
+ const packageStart2 = (0, import_utils.nowMs)();
103
232
  await (0, import_tarPlugin.tarPlugin)(pkg.location, log);
233
+ if (profile) {
234
+ profile.packages.push({
235
+ name: pkg.name,
236
+ targetDir,
237
+ kind: "source",
238
+ durationMs: (0, import_utils.nowMs)() - packageStart2,
239
+ status: "success",
240
+ phases: { tar: (0, import_utils.nowMs)() - packageStart2 }
241
+ });
242
+ }
104
243
  return;
105
244
  }
106
245
  log(`${import_chalk.default.bold((0, import_utils.toUnixPath)(pkg.location.replace(import_constant.PACKAGES_PATH, "").slice(1)))} build start`);
107
246
  const userConfig = (0, import_utils.getUserConfig)(pkg.location);
247
+ const packageStart = (0, import_utils.nowMs)();
248
+ const phaseDurations = {};
249
+ let status = "success";
250
+ const runPhase = async (phaseName, task) => {
251
+ const phaseStart = (0, import_utils.nowMs)();
252
+ await task();
253
+ phaseDurations[phaseName] = (phaseDurations[phaseName] || 0) + ((0, import_utils.nowMs)() - phaseStart);
254
+ };
108
255
  if (packageJson?.scripts?.prebuild) {
109
256
  log("prebuild");
110
- await runScript(["prebuild"], pkg.location);
111
- await packageJson.prebuild(pkg.location);
257
+ await runPhase("prebuild", async () => {
258
+ await (0, import_utils.runScript)(["prebuild"], pkg.location);
259
+ await packageJson.prebuild(pkg.location);
260
+ });
112
261
  }
113
262
  if (userConfig.beforeBuild) {
114
263
  log("beforeBuild");
115
- await userConfig.beforeBuild(log);
116
- }
117
- await doBuildPackage(pkg.location, userConfig, sourcemap, log);
118
- if (!noDeclaration) {
119
- log("build declaration");
120
- await (0, import_buildDeclaration.buildDeclaration)(pkg.location, targetDir);
121
- }
122
- if (packageJson?.scripts?.postbuild) {
123
- log("postbuild");
124
- await runScript(["postbuild"], pkg.location);
125
- }
126
- if (userConfig.afterBuild) {
127
- log("afterBuild");
128
- await userConfig.afterBuild(log);
264
+ await runPhase("beforeBuild", async () => {
265
+ await userConfig.beforeBuild(log);
266
+ });
129
267
  }
130
- await (0, import_addlicense.addLicense)(import_path.default.join(pkg.location, targetDir), log);
131
- if (hasTar) {
132
- await (0, import_tarPlugin.tarPlugin)(pkg.location, log);
268
+ try {
269
+ await runPhase("build", async () => {
270
+ await doBuildPackage(pkg.location, userConfig, sourcemap, log);
271
+ });
272
+ if (packageJson?.scripts?.postbuild) {
273
+ log("postbuild");
274
+ await runPhase("postbuild", async () => {
275
+ await (0, import_utils.runScript)(["postbuild"], pkg.location);
276
+ });
277
+ }
278
+ if (userConfig.afterBuild) {
279
+ log("afterBuild");
280
+ await runPhase("afterBuild", async () => {
281
+ await userConfig.afterBuild(log);
282
+ });
283
+ }
284
+ await runPhase("addLicense", async () => {
285
+ await (0, import_addlicense.addLicense)(import_path.default.join(pkg.location, targetDir), log);
286
+ });
287
+ if (hasTar) {
288
+ await runPhase("tar", async () => {
289
+ await (0, import_tarPlugin.tarPlugin)(pkg.location, log);
290
+ });
291
+ }
292
+ } catch (error) {
293
+ status = "failed";
294
+ (0, import_utils.writeToCache)(BUILD_ERROR, { pkg: pkg.name });
295
+ throw error;
296
+ } finally {
297
+ if (profile) {
298
+ profile.packages.push({
299
+ name: pkg.name,
300
+ targetDir,
301
+ kind: "source",
302
+ durationMs: (0, import_utils.nowMs)() - packageStart,
303
+ status,
304
+ phases: phaseDurations
305
+ });
306
+ if (ENABLE_BUILD_PROFILE) {
307
+ const summary = Object.entries(phaseDurations).sort((a, b) => b[1] - a[1]).map(([name, duration]) => `${name}=${(0, import_utils.formatDuration)(duration)}`).join(", ");
308
+ console.log(
309
+ import_chalk.default.gray(
310
+ `[@nocobase/build:profile] ${pkg.name} ${status} in ${(0, import_utils.formatDuration)((0, import_utils.nowMs)() - packageStart)}${summary ? ` (${summary})` : ""}`
311
+ )
312
+ );
313
+ }
314
+ }
133
315
  }
134
316
  }
135
- function runScript(args, cwd, envs = {}) {
136
- return (0, import_execa.default)("yarn", args, {
137
- cwd,
138
- stdio: "inherit",
139
- env: {
140
- ...process.env,
141
- ...envs,
142
- sourcemap: process.argv.includes("--sourcemap") ? "sourcemap" : void 0,
143
- NODE_ENV: process.env.NODE_ENV || "production"
317
+ async function buildPackageDeclarationLifecycle(pkg, targetDir, profile = null) {
318
+ const log = (0, import_utils.getPkgLog)(pkg.name);
319
+ const packageStart = (0, import_utils.nowMs)();
320
+ const phaseDurations = {};
321
+ let status = "success";
322
+ try {
323
+ log("build declaration");
324
+ const phaseStart = (0, import_utils.nowMs)();
325
+ await (0, import_buildDeclaration.buildDeclaration)(pkg.location, targetDir);
326
+ phaseDurations.declaration = (0, import_utils.nowMs)() - phaseStart;
327
+ } catch (error) {
328
+ status = "failed";
329
+ (0, import_utils.writeToCache)(BUILD_ERROR, { pkg: pkg.name });
330
+ throw error;
331
+ } finally {
332
+ if (profile) {
333
+ profile.packages.push({
334
+ name: pkg.name,
335
+ targetDir,
336
+ kind: "declaration",
337
+ durationMs: (0, import_utils.nowMs)() - packageStart,
338
+ status,
339
+ phases: phaseDurations
340
+ });
341
+ if (ENABLE_BUILD_PROFILE) {
342
+ const summary = Object.entries(phaseDurations).sort((a, b) => b[1] - a[1]).map(([name, duration]) => `${name}=${(0, import_utils.formatDuration)(duration)}`).join(", ");
343
+ console.log(
344
+ import_chalk.default.gray(
345
+ `[@nocobase/build:profile] ${pkg.name} declaration ${status} in ${(0, import_utils.formatDuration)((0, import_utils.nowMs)() - packageStart)}${summary ? ` (${summary})` : ""}`
346
+ )
347
+ );
348
+ }
144
349
  }
145
- });
350
+ }
146
351
  }
147
352
  // Annotate the CommonJS export names for ESM import in node:
148
353
  0 && (module.exports = {
149
354
  build,
150
- buildPackage,
151
355
  buildPackages
152
356
  });
package/lib/buildCjs.js CHANGED
@@ -39,28 +39,33 @@ function buildCjs(cwd, userConfig, sourcemap = false, log) {
39
39
  log("build cjs");
40
40
  const entry = import_fast_glob.default.globSync(["src/**", ...import_constant.globExcludeFiles], { cwd, absolute: true });
41
41
  const outDir = import_path.default.join(cwd, "lib");
42
- const otherExts = Array.from(new Set(entry.map((item) => import_path.default.extname(item)).filter((item) => !import_constant.EsbuildSupportExts.includes(item))));
42
+ const otherExts = Array.from(
43
+ new Set(entry.map((item) => import_path.default.extname(item)).filter((item) => !import_constant.EsbuildSupportExts.includes(item)))
44
+ );
43
45
  if (otherExts.length) {
44
46
  log("%s will not be processed, only be copied to the lib directory.", import_chalk.default.yellow(otherExts.join(",")));
45
47
  }
46
- return (0, import_tsup.build)(userConfig.modifyTsupConfig({
47
- entry,
48
- splitting: false,
49
- clean: true,
50
- bundle: false,
51
- silent: true,
52
- sourcemap,
53
- treeshake: false,
54
- target: "node16",
55
- keepNames: true,
56
- outDir,
57
- loader: {
58
- ...otherExts.reduce((prev, cur) => ({ ...prev, [cur]: "copy" }), {}),
59
- ".json": "copy"
60
- },
61
- format: "cjs",
62
- skipNodeModulesBundle: true
63
- }));
48
+ return (0, import_tsup.build)(
49
+ userConfig.modifyTsupConfig({
50
+ entry,
51
+ splitting: false,
52
+ clean: true,
53
+ bundle: false,
54
+ silent: true,
55
+ sourcemap,
56
+ treeshake: false,
57
+ target: "node16",
58
+ keepNames: true,
59
+ outDir,
60
+ loader: {
61
+ ...otherExts.reduce((prev, cur) => ({ ...prev, [cur]: "copy" }), {}),
62
+ ".json": "copy",
63
+ ".txt": "copy"
64
+ },
65
+ format: "cjs",
66
+ skipNodeModulesBundle: true
67
+ })
68
+ );
64
69
  }
65
70
  // Annotate the CommonJS export names for ESM import in node:
66
71
  0 && (module.exports = {
@@ -31,13 +31,14 @@ __export(buildClient_exports, {
31
31
  buildLocale: () => buildLocale
32
32
  });
33
33
  module.exports = __toCommonJS(buildClient_exports);
34
- var import_plugin_react = __toESM(require("@vitejs/plugin-react"));
34
+ var import_core = require("@rsbuild/core");
35
+ var import_plugin_less = require("@rsbuild/plugin-less");
36
+ var import_plugin_react = require("@rsbuild/plugin-react");
37
+ var import_plugin_svgr = require("@rsbuild/plugin-svgr");
35
38
  var import_fast_glob = __toESM(require("fast-glob"));
36
39
  var import_fs_extra = __toESM(require("fs-extra"));
37
40
  var import_path = __toESM(require("path"));
38
41
  var import_tsup = require("tsup");
39
- var import_vite = require("vite");
40
- var import_vite_plugin_lib_inject_css = require("vite-plugin-lib-inject-css");
41
42
  var import_constant = require("./constant");
42
43
  var import_utils = require("./utils");
43
44
  async function buildClient(cwd, userConfig, sourcemap = false, log) {
@@ -45,7 +46,7 @@ async function buildClient(cwd, userConfig, sourcemap = false, log) {
45
46
  const cwdWin = cwd.replaceAll(/\\/g, "/");
46
47
  const cwdUnix = cwd.replaceAll(/\//g, "\\");
47
48
  const external = function(id) {
48
- if (id.startsWith(".") || id.startsWith(cwdUnix) || id.startsWith(cwdWin)) {
49
+ if (!id || import_path.default.isAbsolute(id) || id.startsWith(".") || id.startsWith(cwdUnix) || id.startsWith(cwdWin)) {
49
50
  return false;
50
51
  }
51
52
  return true;
@@ -54,35 +55,12 @@ async function buildClient(cwd, userConfig, sourcemap = false, log) {
54
55
  await buildClientLib(cwd, userConfig, sourcemap, external, log);
55
56
  await buildLocale(cwd, userConfig, log);
56
57
  }
57
- function buildClientEsm(cwd, userConfig, sourcemap, external, log) {
58
+ async function buildClientEsm(cwd, userConfig, sourcemap, external, log) {
58
59
  log("build client esm");
59
60
  const entry = import_path.default.join(cwd, "src/index.ts").replaceAll(/\\/g, "/");
60
61
  const outDir = import_path.default.resolve(cwd, "es");
61
- return (0, import_vite.build)(
62
- userConfig.modifyViteConfig({
63
- mode: process.env.NODE_ENV || "production",
64
- define: (0, import_utils.getEnvDefine)(),
65
- build: {
66
- minify: process.env.NODE_ENV === "production",
67
- outDir,
68
- cssCodeSplit: true,
69
- emptyOutDir: true,
70
- sourcemap,
71
- lib: {
72
- entry,
73
- formats: ["es"],
74
- fileName: "index"
75
- },
76
- target: ["es2015", "edge88", "firefox78", "chrome87", "safari14"],
77
- rollupOptions: {
78
- cache: true,
79
- treeshake: true,
80
- external
81
- }
82
- },
83
- plugins: [(0, import_plugin_react.default)(), (0, import_vite_plugin_lib_inject_css.libInjectCss)()]
84
- })
85
- );
62
+ await buildClientWithRsbuild(cwd, userConfig, sourcemap, external, entry, outDir, "esm");
63
+ await injectEntryStyleReference(import_path.default.join(outDir, "index.mjs"), 'import "./index.css";');
86
64
  }
87
65
  async function buildClientLib(cwd, userConfig, sourcemap, external, log) {
88
66
  log("build client lib");
@@ -91,32 +69,114 @@ async function buildClientLib(cwd, userConfig, sourcemap, external, log) {
91
69
  const entry = import_path.default.join(esDir, "index.ts");
92
70
  import_fs_extra.default.removeSync(entry);
93
71
  import_fs_extra.default.linkSync(import_path.default.join(cwd, "es/index.mjs"), entry);
94
- await (0, import_vite.build)(
95
- userConfig.modifyViteConfig({
96
- mode: process.env.NODE_ENV || "production",
97
- esbuild: {
98
- format: "cjs"
72
+ try {
73
+ await buildClientWithRsbuild(cwd, userConfig, sourcemap, external, entry, outDir, "cjs");
74
+ } finally {
75
+ import_fs_extra.default.removeSync(entry);
76
+ }
77
+ await injectEntryStyleReference(import_path.default.join(outDir, "index.js"), 'require("./index.css");');
78
+ }
79
+ async function buildClientWithRsbuild(cwd, userConfig, sourcemap, external, entry, outDir, format) {
80
+ const config = createClientRsbuildConfig(cwd, entry, outDir, sourcemap, external, format);
81
+ const rsbuild = await (0, import_core.createRsbuild)({
82
+ cwd,
83
+ config: userConfig.modifyRsbuildConfig?.(config) ?? config
84
+ });
85
+ const result = await rsbuild.build();
86
+ await result.close();
87
+ }
88
+ function createClientRsbuildConfig(cwd, entry, outDir, sourcemap, external, format) {
89
+ return {
90
+ plugins: [(0, import_plugin_react.pluginReact)(), (0, import_plugin_less.pluginLess)(), (0, import_plugin_svgr.pluginSvgr)()],
91
+ source: {
92
+ entry: {
93
+ index: {
94
+ import: entry,
95
+ html: false
96
+ }
97
+ },
98
+ tsconfigPath: import_path.default.join(cwd, "tsconfig.json"),
99
+ define: (0, import_utils.getEnvDefine)(),
100
+ decorators: {
101
+ version: "legacy"
102
+ }
103
+ },
104
+ output: {
105
+ target: "web",
106
+ distPath: {
107
+ root: outDir,
108
+ js: ".",
109
+ jsAsync: ".",
110
+ css: ".",
111
+ cssAsync: ".",
112
+ svg: ".",
113
+ font: ".",
114
+ image: ".",
115
+ media: ".",
116
+ assets: "."
99
117
  },
100
- build: {
101
- outDir,
102
- minify: process.env.NODE_ENV === "production",
103
- sourcemap,
104
- lib: {
105
- entry: import_path.default.join(cwd, "es/index.ts"),
106
- formats: ["cjs"],
107
- fileName: "index"
108
- },
109
- rollupOptions: {
110
- external
118
+ filename: {
119
+ js: format === "esm" ? "[name].mjs" : "[name].js",
120
+ css: "[name].css",
121
+ svg: "[name][ext][query]",
122
+ font: "[name][ext][query]",
123
+ image: "[name][ext][query]",
124
+ media: "[name][ext][query]",
125
+ assets: "[name][ext][query]"
126
+ },
127
+ cleanDistPath: true,
128
+ sourceMap: sourcemap,
129
+ minify: process.env.NODE_ENV === "production",
130
+ emitCss: true,
131
+ externals: [
132
+ function({ request }, callback) {
133
+ if (request && external(request)) {
134
+ return callback(null, true);
135
+ }
136
+ callback();
111
137
  }
138
+ ]
139
+ },
140
+ performance: {
141
+ chunkSplit: {
142
+ strategy: "all-in-one"
112
143
  }
113
- })
114
- );
115
- import_fs_extra.default.removeSync(entry);
116
- const css = import_fast_glob.default.sync("*.css", { cwd: esDir, absolute: true });
117
- css.forEach((file) => {
118
- import_fs_extra.default.copySync(file, import_path.default.join(outDir, import_path.default.basename(file)));
119
- });
144
+ },
145
+ tools: {
146
+ rspack(config) {
147
+ config.output = config.output || {};
148
+ config.output.asyncChunks = false;
149
+ if (format === "esm") {
150
+ config.output.library = { type: "module" };
151
+ config.output.module = true;
152
+ config.output.chunkFormat = "module";
153
+ config.output.chunkLoading = "import";
154
+ config.output.workerChunkLoading = "import";
155
+ config.experiments = {
156
+ ...config.experiments,
157
+ outputModule: true
158
+ };
159
+ config.externalsType = "module-import";
160
+ } else {
161
+ config.output.library = { type: "commonjs-static" };
162
+ }
163
+ config.performance = false;
164
+ config.stats = "errors-warnings";
165
+ }
166
+ }
167
+ };
168
+ }
169
+ async function injectEntryStyleReference(entryFile, styleReference) {
170
+ const cssFile = import_path.default.join(import_path.default.dirname(entryFile), "index.css");
171
+ if (!import_fs_extra.default.existsSync(entryFile) || !import_fs_extra.default.existsSync(cssFile)) {
172
+ return;
173
+ }
174
+ const content = await import_fs_extra.default.readFile(entryFile, "utf8");
175
+ if (content.startsWith(styleReference)) {
176
+ return;
177
+ }
178
+ await import_fs_extra.default.writeFile(entryFile, `${styleReference}
179
+ ${content}`);
120
180
  }
121
181
  function buildLocale(cwd, userConfig, log) {
122
182
  log("build client locale");