@modern-js/app-tools 2.0.0-beta.1 → 2.0.0-beta.3

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.
Files changed (240) hide show
  1. package/CHANGELOG.md +445 -0
  2. package/bin/modern.js +10 -1
  3. package/dist/js/modern/analyze/constants.js +2 -0
  4. package/dist/js/modern/analyze/generateCode.js +39 -19
  5. package/dist/js/modern/analyze/getBundleEntry.js +1 -1
  6. package/dist/js/modern/analyze/getFileSystemEntry.js +1 -1
  7. package/dist/js/modern/analyze/getHtmlTemplate.js +1 -1
  8. package/dist/js/modern/analyze/getServerRoutes.js +8 -4
  9. package/dist/js/modern/analyze/index.js +12 -27
  10. package/dist/js/modern/analyze/nestedRoutes.js +17 -6
  11. package/dist/js/modern/analyze/templates.js +59 -27
  12. package/dist/js/modern/analyze/utils.js +30 -4
  13. package/dist/js/modern/builder/builderPlugins/compatModern.js +18 -12
  14. package/dist/js/modern/builder/index.js +31 -16
  15. package/dist/js/modern/builder/loaders/routerLoader.js +20 -0
  16. package/dist/js/modern/builder/loaders/serverModuleLoader.js +4 -0
  17. package/dist/js/modern/builder/share.js +1 -1
  18. package/dist/js/modern/commands/build.js +8 -2
  19. package/dist/js/modern/commands/dev.js +37 -32
  20. package/dist/js/modern/commands/inspect.js +4 -2
  21. package/dist/js/modern/config/default.js +206 -0
  22. package/dist/js/modern/config/index.js +2 -0
  23. package/dist/js/modern/config/initial/createHtmlConfig.js +32 -0
  24. package/dist/js/modern/{builder → config/initial}/createOutputConfig.js +16 -15
  25. package/dist/js/modern/config/initial/createSourceConfig.js +32 -0
  26. package/dist/js/modern/config/initial/createToolsConfig.js +41 -0
  27. package/dist/js/modern/config/initial/index.js +11 -0
  28. package/dist/js/modern/config/initial/inits.js +117 -0
  29. package/dist/js/modern/config/initial/transformNormalizedConfig.js +40 -0
  30. package/dist/js/modern/defineConfig.js +12 -0
  31. package/dist/js/modern/hooks.js +23 -19
  32. package/dist/js/modern/index.js +7 -5
  33. package/dist/js/modern/initialize/index.js +72 -0
  34. package/dist/js/modern/schema/Schema.js +39 -0
  35. package/dist/js/modern/schema/index.js +139 -0
  36. package/dist/js/modern/schema/legacy.js +284 -0
  37. package/dist/js/modern/types/config/deploy.js +0 -0
  38. package/dist/js/modern/types/config/dev.js +0 -0
  39. package/dist/js/modern/types/config/experiments.js +0 -0
  40. package/dist/js/modern/types/config/html.js +0 -0
  41. package/dist/js/modern/types/config/index.js +2 -0
  42. package/dist/js/modern/types/config/output.js +0 -0
  43. package/dist/js/modern/types/config/performance.js +0 -0
  44. package/dist/js/modern/types/config/security.js +0 -0
  45. package/dist/js/modern/types/config/source.js +0 -0
  46. package/dist/js/modern/types/config/tools.js +0 -0
  47. package/dist/js/modern/types/hooks.js +0 -0
  48. package/dist/js/modern/types/index.js +4 -0
  49. package/dist/js/modern/types/legacyConfig/deploy.js +0 -0
  50. package/dist/js/modern/types/legacyConfig/dev.js +0 -0
  51. package/dist/js/modern/types/legacyConfig/index.js +0 -0
  52. package/dist/js/modern/types/legacyConfig/output.js +1 -0
  53. package/dist/js/modern/types/legacyConfig/source.js +0 -0
  54. package/dist/js/modern/types/legacyConfig/tools.js +0 -0
  55. package/dist/js/modern/utils/config.js +1 -1
  56. package/dist/js/modern/utils/createFileWatcher.js +82 -0
  57. package/dist/js/modern/utils/restart.js +17 -0
  58. package/dist/js/node/analyze/constants.js +5 -1
  59. package/dist/js/node/analyze/generateCode.js +37 -17
  60. package/dist/js/node/analyze/getBundleEntry.js +1 -1
  61. package/dist/js/node/analyze/getFileSystemEntry.js +1 -1
  62. package/dist/js/node/analyze/getHtmlTemplate.js +1 -1
  63. package/dist/js/node/analyze/getServerRoutes.js +8 -4
  64. package/dist/js/node/analyze/index.js +13 -39
  65. package/dist/js/node/analyze/nestedRoutes.js +15 -4
  66. package/dist/js/node/analyze/templates.js +60 -27
  67. package/dist/js/node/analyze/utils.js +31 -3
  68. package/dist/js/node/builder/builderPlugins/compatModern.js +18 -12
  69. package/dist/js/node/builder/index.js +32 -16
  70. package/dist/js/node/builder/loaders/routerLoader.js +27 -0
  71. package/dist/js/node/builder/loaders/serverModuleLoader.js +11 -0
  72. package/dist/js/node/builder/share.js +1 -1
  73. package/dist/js/node/commands/build.js +8 -2
  74. package/dist/js/node/commands/dev.js +37 -32
  75. package/dist/js/node/commands/inspect.js +4 -2
  76. package/dist/js/node/config/default.js +213 -0
  77. package/dist/js/node/config/index.js +31 -0
  78. package/dist/js/node/config/initial/createHtmlConfig.js +38 -0
  79. package/dist/js/node/{builder → config/initial}/createOutputConfig.js +16 -15
  80. package/dist/js/node/config/initial/createSourceConfig.js +38 -0
  81. package/dist/js/node/config/initial/createToolsConfig.js +47 -0
  82. package/dist/js/node/config/initial/index.js +24 -0
  83. package/dist/js/node/config/initial/inits.js +127 -0
  84. package/dist/js/node/config/initial/transformNormalizedConfig.js +46 -0
  85. package/dist/js/node/defineConfig.js +20 -0
  86. package/dist/js/node/hooks.js +23 -28
  87. package/dist/js/node/index.js +30 -16
  88. package/dist/js/node/initialize/index.js +79 -0
  89. package/dist/js/node/schema/Schema.js +46 -0
  90. package/dist/js/node/schema/index.js +152 -0
  91. package/dist/js/node/schema/legacy.js +291 -0
  92. package/dist/js/node/types/config/deploy.js +0 -0
  93. package/dist/js/node/types/config/dev.js +0 -0
  94. package/dist/js/node/types/config/experiments.js +0 -0
  95. package/dist/js/node/types/config/html.js +0 -0
  96. package/dist/js/node/types/config/index.js +16 -0
  97. package/dist/js/node/types/config/output.js +0 -0
  98. package/dist/js/node/types/config/performance.js +0 -0
  99. package/dist/js/node/types/config/security.js +0 -0
  100. package/dist/js/node/types/config/source.js +0 -0
  101. package/dist/js/node/types/config/tools.js +0 -0
  102. package/dist/js/node/types/hooks.js +0 -0
  103. package/dist/js/node/types/index.js +38 -0
  104. package/dist/js/node/types/legacyConfig/deploy.js +0 -0
  105. package/dist/js/node/types/legacyConfig/dev.js +0 -0
  106. package/dist/js/node/types/legacyConfig/index.js +0 -0
  107. package/dist/js/node/types/legacyConfig/output.js +5 -0
  108. package/dist/js/node/types/legacyConfig/source.js +0 -0
  109. package/dist/js/node/types/legacyConfig/tools.js +0 -0
  110. package/dist/js/node/utils/config.js +1 -1
  111. package/dist/js/node/utils/createFileWatcher.js +91 -0
  112. package/dist/js/node/utils/restart.js +23 -0
  113. package/dist/js/treeshaking/analyze/constants.js +2 -0
  114. package/dist/js/treeshaking/analyze/generateCode.js +138 -82
  115. package/dist/js/treeshaking/analyze/getBundleEntry.js +1 -1
  116. package/dist/js/treeshaking/analyze/getFileSystemEntry.js +1 -1
  117. package/dist/js/treeshaking/analyze/getHtmlTemplate.js +1 -1
  118. package/dist/js/treeshaking/analyze/getServerRoutes.js +7 -5
  119. package/dist/js/treeshaking/analyze/index.js +10 -26
  120. package/dist/js/treeshaking/analyze/nestedRoutes.js +98 -55
  121. package/dist/js/treeshaking/analyze/templates.js +175 -101
  122. package/dist/js/treeshaking/analyze/utils.js +80 -4
  123. package/dist/js/treeshaking/builder/builderPlugins/compatModern.js +18 -12
  124. package/dist/js/treeshaking/builder/index.js +29 -16
  125. package/dist/js/treeshaking/builder/loaders/routerLoader.js +14 -0
  126. package/dist/js/treeshaking/builder/loaders/serverModuleLoader.js +4 -0
  127. package/dist/js/treeshaking/builder/share.js +1 -1
  128. package/dist/js/treeshaking/commands/build.js +33 -23
  129. package/dist/js/treeshaking/commands/dev.js +56 -43
  130. package/dist/js/treeshaking/commands/inspect.js +8 -3
  131. package/dist/js/treeshaking/config/default.js +199 -0
  132. package/dist/js/treeshaking/config/index.js +2 -0
  133. package/dist/js/treeshaking/config/initial/createHtmlConfig.js +31 -0
  134. package/dist/js/treeshaking/config/initial/createOutputConfig.js +70 -0
  135. package/dist/js/treeshaking/config/initial/createSourceConfig.js +41 -0
  136. package/dist/js/treeshaking/config/initial/createToolsConfig.js +38 -0
  137. package/dist/js/treeshaking/config/initial/index.js +11 -0
  138. package/dist/js/treeshaking/config/initial/inits.js +114 -0
  139. package/dist/js/treeshaking/config/initial/transformNormalizedConfig.js +38 -0
  140. package/dist/js/treeshaking/defineConfig.js +14 -0
  141. package/dist/js/treeshaking/hooks.js +23 -19
  142. package/dist/js/treeshaking/index.js +7 -5
  143. package/dist/js/treeshaking/initialize/index.js +121 -0
  144. package/dist/js/treeshaking/schema/Schema.js +75 -0
  145. package/dist/js/treeshaking/schema/index.js +138 -0
  146. package/dist/js/treeshaking/schema/legacy.js +273 -0
  147. package/dist/js/treeshaking/types/config/deploy.js +0 -0
  148. package/dist/js/treeshaking/types/config/dev.js +0 -0
  149. package/dist/js/treeshaking/types/config/experiments.js +0 -0
  150. package/dist/js/treeshaking/types/config/html.js +0 -0
  151. package/dist/js/treeshaking/types/config/index.js +2 -0
  152. package/dist/js/treeshaking/types/config/output.js +0 -0
  153. package/dist/js/treeshaking/types/config/performance.js +0 -0
  154. package/dist/js/treeshaking/types/config/security.js +0 -0
  155. package/dist/js/treeshaking/types/config/source.js +0 -0
  156. package/dist/js/treeshaking/types/config/tools.js +0 -0
  157. package/dist/js/treeshaking/types/hooks.js +0 -0
  158. package/dist/js/treeshaking/types/index.js +4 -0
  159. package/dist/js/treeshaking/types/legacyConfig/deploy.js +0 -0
  160. package/dist/js/treeshaking/types/legacyConfig/dev.js +0 -0
  161. package/dist/js/treeshaking/types/legacyConfig/index.js +0 -0
  162. package/dist/js/treeshaking/types/legacyConfig/output.js +1 -0
  163. package/dist/js/treeshaking/types/legacyConfig/source.js +0 -0
  164. package/dist/js/treeshaking/types/legacyConfig/tools.js +0 -0
  165. package/dist/js/treeshaking/utils/config.js +1 -1
  166. package/dist/js/treeshaking/utils/createFileWatcher.js +123 -0
  167. package/dist/js/treeshaking/utils/restart.js +45 -0
  168. package/dist/types/analyze/constants.d.ts +2 -0
  169. package/dist/types/analyze/generateCode.d.ts +3 -2
  170. package/dist/types/analyze/getBundleEntry.d.ts +2 -2
  171. package/dist/types/analyze/getFileSystemEntry.d.ts +2 -2
  172. package/dist/types/analyze/getHtmlTemplate.d.ts +3 -3
  173. package/dist/types/analyze/getServerRoutes.d.ts +3 -2
  174. package/dist/types/analyze/index.d.ts +3 -41
  175. package/dist/types/analyze/templates.d.ts +9 -8
  176. package/dist/types/analyze/utils.d.ts +10 -2
  177. package/dist/types/builder/builderPlugins/compatModern.d.ts +2 -2
  178. package/dist/types/builder/index.d.ts +5 -2
  179. package/dist/types/builder/loaders/routerLoader.d.ts +3 -0
  180. package/dist/types/builder/loaders/serverModuleLoader.d.ts +3 -0
  181. package/dist/types/builder/share.d.ts +2 -2
  182. package/dist/types/commands/build.d.ts +2 -2
  183. package/dist/types/commands/deploy.d.ts +2 -2
  184. package/dist/types/commands/dev.d.ts +2 -2
  185. package/dist/types/commands/inspect.d.ts +9 -1
  186. package/dist/types/commands/start.d.ts +2 -2
  187. package/dist/types/config/default.d.ts +3 -0
  188. package/dist/types/config/index.d.ts +2 -0
  189. package/dist/types/config/initial/createHtmlConfig.d.ts +2 -0
  190. package/dist/types/config/initial/createOutputConfig.d.ts +2 -0
  191. package/dist/types/config/initial/createSourceConfig.d.ts +2 -0
  192. package/dist/types/config/initial/createToolsConfig.d.ts +2 -0
  193. package/dist/types/config/initial/index.d.ts +4 -0
  194. package/dist/types/config/initial/inits.d.ts +4 -0
  195. package/dist/types/config/initial/transformNormalizedConfig.d.ts +2 -0
  196. package/dist/types/defineConfig.d.ts +7 -0
  197. package/dist/types/hooks.d.ts +2 -42
  198. package/dist/types/index.d.ts +5 -5
  199. package/dist/types/initialize/index.d.ts +3 -0
  200. package/dist/types/schema/Schema.d.ts +14 -0
  201. package/dist/types/schema/index.d.ts +4 -0
  202. package/dist/types/schema/legacy.d.ts +3 -0
  203. package/dist/types/types/config/deploy.d.ts +9 -0
  204. package/dist/types/types/config/dev.d.ts +13 -0
  205. package/dist/types/types/config/experiments.d.ts +4 -0
  206. package/dist/types/types/config/html.d.ts +4 -0
  207. package/dist/types/types/config/index.d.ts +62 -0
  208. package/dist/types/types/config/output.d.ts +23 -0
  209. package/dist/types/types/config/performance.d.ts +4 -0
  210. package/dist/types/types/config/security.d.ts +4 -0
  211. package/dist/types/types/config/source.d.ts +22 -0
  212. package/dist/types/types/config/tools.d.ts +22 -0
  213. package/dist/types/types/hooks.d.ts +81 -0
  214. package/dist/types/types/index.d.ts +23 -0
  215. package/dist/types/types/legacyConfig/deploy.d.ts +8 -0
  216. package/dist/types/types/legacyConfig/dev.d.ts +12 -0
  217. package/dist/types/types/legacyConfig/index.d.ts +33 -0
  218. package/dist/types/types/legacyConfig/output.d.ts +51 -0
  219. package/dist/types/types/legacyConfig/source.d.ts +25 -0
  220. package/dist/types/types/legacyConfig/tools.d.ts +16 -0
  221. package/dist/types/utils/config.d.ts +2 -2
  222. package/dist/types/utils/createFileWatcher.d.ts +4 -0
  223. package/dist/types/utils/printInstructions.d.ts +3 -3
  224. package/dist/types/utils/restart.d.ts +3 -0
  225. package/lib/types.d.ts +1 -1
  226. package/package.json +28 -25
  227. package/dist/js/modern/builder/createHtmlConfig.js +0 -58
  228. package/dist/js/modern/builder/createSourceConfig.js +0 -74
  229. package/dist/js/modern/builder/createToolsConfig.js +0 -87
  230. package/dist/js/node/builder/createHtmlConfig.js +0 -68
  231. package/dist/js/node/builder/createSourceConfig.js +0 -82
  232. package/dist/js/node/builder/createToolsConfig.js +0 -94
  233. package/dist/js/treeshaking/builder/createHtmlConfig.js +0 -59
  234. package/dist/js/treeshaking/builder/createOutputConfig.js +0 -70
  235. package/dist/js/treeshaking/builder/createSourceConfig.js +0 -88
  236. package/dist/js/treeshaking/builder/createToolsConfig.js +0 -85
  237. package/dist/types/builder/createHtmlConfig.d.ts +0 -6
  238. package/dist/types/builder/createOutputConfig.d.ts +0 -3
  239. package/dist/types/builder/createSourceConfig.d.ts +0 -5
  240. package/dist/types/builder/createToolsConfig.d.ts +0 -13
@@ -2,7 +2,6 @@ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (O
2
2
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
3
3
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
4
4
  import * as path from 'path';
5
- import { createAsyncWaterfall } from '@modern-js/plugin';
6
5
  import { createDebugger, fs, isApiOnly } from '@modern-js/utils';
7
6
  import { cloneDeep } from '@modern-js/utils/lodash';
8
7
  import { createBuilderForEdenX } from "../builder";
@@ -10,34 +9,11 @@ import { printInstructions } from "../utils/printInstructions";
10
9
  import { generateRoutes } from "../utils/routes";
11
10
  import { emitResolvedConfig } from "../utils/config";
12
11
  import { getCommand } from "../utils/commands";
12
+ import { initialNormalizedConfig } from "../config";
13
13
  import { isRouteComponentFile } from "./utils";
14
14
  const debug = createDebugger('plugin-analyze');
15
- export const modifyEntryImports = createAsyncWaterfall();
16
- export const modifyEntryExport = createAsyncWaterfall();
17
- export const addRuntimeExports = createAsyncWaterfall();
18
- export const modifyEntryRuntimePlugins = createAsyncWaterfall();
19
- export const modifyEntryRenderFunction = createAsyncWaterfall();
20
- export const modifyAsyncEntry = createAsyncWaterfall();
21
- export const modifyFileSystemRoutes = createAsyncWaterfall();
22
- export const modifyServerRoutes = createAsyncWaterfall();
23
- export const htmlPartials = createAsyncWaterfall();
24
- export const beforeGenerateRoutes = createAsyncWaterfall();
25
- export const addDefineTypes = createAsyncWaterfall();
26
15
  export default (() => ({
27
16
  name: '@modern-js/plugin-analyze',
28
- registerHook: {
29
- modifyAsyncEntry,
30
- modifyEntryImports,
31
- modifyEntryExport,
32
- modifyEntryRuntimePlugins,
33
- modifyEntryRenderFunction,
34
- modifyFileSystemRoutes,
35
- modifyServerRoutes,
36
- htmlPartials,
37
- addRuntimeExports,
38
- beforeGenerateRoutes,
39
- addDefineTypes
40
- },
41
17
  setup: api => {
42
18
  let pagesDir = [];
43
19
  let originEntrypoints = [];
@@ -52,7 +28,7 @@ export default (() => ({
52
28
  } catch (_unused) {
53
29
  // FIXME:
54
30
  }
55
- const apiOnly = await isApiOnly(appContext.appDirectory, resolvedConfig === null || resolvedConfig === void 0 ? void 0 : (_resolvedConfig$sourc = resolvedConfig.source) === null || _resolvedConfig$sourc === void 0 ? void 0 : _resolvedConfig$sourc.entriesDir);
31
+ const apiOnly = await isApiOnly(appContext.appDirectory, (_resolvedConfig$sourc = resolvedConfig.source) === null || _resolvedConfig$sourc === void 0 ? void 0 : _resolvedConfig$sourc.entriesDir);
56
32
  await hookRunners.addRuntimeExports();
57
33
  if (apiOnly) {
58
34
  const {
@@ -119,7 +95,7 @@ export default (() => ({
119
95
  if (buildCommands.includes(command)) {
120
96
  const normalizedConfig = api.useResolvedConfigContext();
121
97
  const builder = await createBuilderForEdenX({
122
- normalizedConfig,
98
+ normalizedConfig: normalizedConfig,
123
99
  appContext,
124
100
  compatPluginConfig: {
125
101
  async onBeforeBuild({
@@ -180,6 +156,15 @@ export default (() => ({
180
156
  watchFiles() {
181
157
  return pagesDir;
182
158
  },
159
+ resolvedConfig({
160
+ resolved
161
+ }) {
162
+ const appContext = api.useAppContext();
163
+ const config = initialNormalizedConfig(resolved, appContext);
164
+ return {
165
+ resolved: config
166
+ };
167
+ },
183
168
  async fileChange(e) {
184
169
  const appContext = api.useAppContext();
185
170
  const {
@@ -2,15 +2,21 @@ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (O
2
2
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
3
3
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
4
4
  import * as path from 'path';
5
- import { fs, getRouteId } from '@modern-js/utils';
5
+ import { fs, getRouteId, normalizeToPosixPath } from '@modern-js/utils';
6
6
  import { JS_EXTENSIONS } from "./constants";
7
- import { replaceWithAlias } from "./utils";
7
+ import { hasLoader, replaceWithAlias } from "./utils";
8
8
  const LAYOUT_FILE = 'layout';
9
9
  const PAGE_FILE = 'page';
10
10
  const LOADING_FILE = 'loading';
11
11
  const ERROR_FILE = 'error';
12
12
  const LOADER_FILE = 'loader';
13
13
  const conventionNames = [LAYOUT_FILE, PAGE_FILE, LOADING_FILE, ERROR_FILE, LOADER_FILE];
14
+ const getLoaderPath = async filename => {
15
+ if (await hasLoader(filename)) {
16
+ return normalizeToPosixPath(filename);
17
+ }
18
+ return undefined;
19
+ };
14
20
  const replaceDynamicPath = routePath => {
15
21
  return routePath.replace(/\[(.*?)\]/g, ':$1');
16
22
  };
@@ -48,7 +54,8 @@ export const walk = async (dirname, rootDir, alias, entryName) => {
48
54
  routePath = replaceDynamicPath(routePath);
49
55
  const route = {
50
56
  path: routePath,
51
- children: []
57
+ children: [],
58
+ isRoot
52
59
  };
53
60
  const items = await fs.readdir(dirname);
54
61
  for (const item of items) {
@@ -68,17 +75,21 @@ export const walk = async (dirname, rootDir, alias, entryName) => {
68
75
  }
69
76
  if (itemWithoutExt === LAYOUT_FILE) {
70
77
  route._component = replaceWithAlias(alias.basename, itemPath, alias.name);
78
+ route.loader = await getLoaderPath(itemPath);
71
79
  }
72
80
  if (itemWithoutExt === PAGE_FILE) {
73
81
  var _route$children2;
74
82
  const childRoute = createIndexRoute({
75
83
  _component: replaceWithAlias(alias.basename, itemPath, alias.name)
76
84
  }, rootDir, itemPath, entryName);
85
+ childRoute.loader = await getLoaderPath(itemPath);
77
86
  (_route$children2 = route.children) === null || _route$children2 === void 0 ? void 0 : _route$children2.push(childRoute);
78
87
  }
79
- if (itemWithoutExt === LOADER_FILE) {
80
- route.loader = replaceWithAlias(alias.basename, itemPath, alias.name);
81
- }
88
+
89
+ // if (itemWithoutExt === LOADER_FILE) {
90
+ // route.loader = replaceWithAlias(alias.basename, itemPath, alias.name);
91
+ // }
92
+
82
93
  if (itemWithoutExt === LOADING_FILE) {
83
94
  route.loading = replaceWithAlias(alias.basename, itemPath, alias.name);
84
95
  }
@@ -1,6 +1,9 @@
1
1
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2
2
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
3
3
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
4
+ import path from 'path';
5
+ import { fs } from '@modern-js/utils';
6
+ import { TEMP_LOADERS_DIR } from "./constants";
4
7
  export const index = ({
5
8
  mountId,
6
9
  imports,
@@ -78,13 +81,11 @@ export const html = partials => `
78
81
  `;
79
82
  export const routesForServer = ({
80
83
  routes,
81
- alias
84
+ internalDirectory,
85
+ entryName
82
86
  }) => {
83
- const {
84
- name,
85
- basename
86
- } = alias;
87
87
  const loaders = [];
88
+ const loaderIndexFile = path.join(internalDirectory, entryName, TEMP_LOADERS_DIR, 'index.js');
88
89
  const traverseRouteTree = route => {
89
90
  let children;
90
91
  if ('children' in route && route.children) {
@@ -116,38 +117,43 @@ export const routesForServer = ({
116
117
  }
117
118
  }
118
119
  routesCode += `\n];`;
119
- const importLoadersCode = loaders.map((loader, index) => {
120
- const realLoaderPath = loader.replace(name, basename);
121
- return `import loader_${index} from '${realLoaderPath}';\n`;
122
- }).join('');
120
+ let importLoadersCode = '';
121
+ if (loaders.length > 0) {
122
+ importLoadersCode = `
123
+ import { ${loaders.map((loader, index) => `loader_${index}`)} } from "${loaderIndexFile}"`;
124
+ }
123
125
  return `
124
126
  ${importLoadersCode}
125
127
  ${routesCode}
126
128
  `;
127
129
  };
128
- export const fileSystemRoutes = ({
130
+ export const fileSystemRoutes = async ({
129
131
  routes,
130
132
  ssrMode,
131
133
  nestedRoutesEntry,
132
- entryName
134
+ entryName,
135
+ internalDirectory
133
136
  }) => {
134
- // The legacy mode and pages dir routes should use loadable
135
- // nested routes + renderTostring should use loadable.lazy
136
- // nested routes + renderToStream should use react.lazy
137
+ const loadings = [];
138
+ const errors = [];
139
+ const loaders = [];
140
+ const loadersMap = {};
141
+ const loadersIndexFile = path.join('@_modern_js_internal', entryName, TEMP_LOADERS_DIR, 'index.js');
142
+ const loadersMapFile = path.join(internalDirectory, entryName, TEMP_LOADERS_DIR, 'map.json');
137
143
  const importLazyCode = `
138
144
  import { lazy } from "react";
139
145
  import loadable, { lazy as loadableLazy } from "@modern-js/runtime/loadable"
140
146
  `;
147
+ let rootLayoutCode = ``;
141
148
  let dataLoaderPath = '';
149
+ let componentLoaderPath = '';
142
150
  if (ssrMode) {
143
151
  dataLoaderPath = require.resolve(`@modern-js/plugin-data-loader/loader`);
144
152
  if (nestedRoutesEntry) {
145
- dataLoaderPath = `${dataLoaderPath}?routesDir=${nestedRoutesEntry}&entryName=${entryName}!`;
153
+ dataLoaderPath = `${dataLoaderPath}?routesDir=${nestedRoutesEntry}&mapFile=${loadersMapFile}!`;
146
154
  }
155
+ componentLoaderPath = `${path.join(__dirname, '../builder/loaders/routerLoader')}!`;
147
156
  }
148
- const loadings = [];
149
- const errors = [];
150
- const loaders = [];
151
157
  const traverseRouteTree = route => {
152
158
  let children;
153
159
  if ('children' in route && route.children) {
@@ -169,13 +175,19 @@ export const fileSystemRoutes = ({
169
175
  }
170
176
  if (route.loader) {
171
177
  loaders.push(route.loader);
172
- loader = `loader_${loaders.length - 1}`;
178
+ const loaderId = loaders.length - 1;
179
+ loader = `loader_${loaderId}`;
180
+ loadersMap[loader] = route.id;
173
181
  }
174
182
  if (route._component) {
175
- if (ssrMode === 'stream') {
176
- component = `lazy(() => import(/* webpackChunkName: "${route.id}" */ /* webpackMode: "lazy-once" */ '${route._component}'))`;
183
+ if (route.isRoot) {
184
+ rootLayoutCode = `import RootLayout from '${route._component}'`;
185
+ component = `RootLayout`;
186
+ } else if (ssrMode === 'string') {
187
+ component = `loadable(() => import(/* webpackChunkName: "${route.id}" */ '${componentLoaderPath}${route._component}'))`;
177
188
  } else {
178
- component = `loadable(() => import(/* webpackChunkName: "${route.id}" */ /* webpackMode: "lazy-once" */ '${route._component}'))`;
189
+ // csr and streaming
190
+ component = `lazy(() => import(/* webpackChunkName: "${route.id}" */ '${componentLoaderPath}${route._component}'))`;
179
191
  }
180
192
  }
181
193
  } else if (route._component) {
@@ -198,7 +210,7 @@ export const fileSystemRoutes = ({
198
210
  for (const route of routes) {
199
211
  if ('type' in route) {
200
212
  const newRoute = traverseRouteTree(route);
201
- routeComponentsCode += `${JSON.stringify(newRoute, null, 2).replace(/"(loadable.*\))"/g, '$1').replace(/"(loadableLazy.*\))"/g, '$1').replace(/"(lazy.*\))"/g, '$1').replace(/"(loading_[^"])"/g, '$1').replace(/"(loader_[^"])"/g, '$1').replace(/"(error_[^"])"/g, '$1').replace(/\\"/g, '"')},`;
213
+ routeComponentsCode += `${JSON.stringify(newRoute, null, 2).replace(/"(loadable.*\))"/g, '$1').replace(/"(loadableLazy.*\))"/g, '$1').replace(/"(lazy.*\))"/g, '$1').replace(/"(loading_[^"])"/g, '$1').replace(/"(loader_[^"])"/g, '$1').replace(/"(RootLayout)"/g, '$1').replace(/"(error_[^"])"/g, '$1').replace(/\\"/g, '"')},`;
202
214
  } else {
203
215
  const component = `loadable(() => import('${route._component}'))`;
204
216
  const finalRoute = _objectSpread(_objectSpread({}, route), {}, {
@@ -214,14 +226,34 @@ export const fileSystemRoutes = ({
214
226
  const importErrorComponentsCode = errors.map((error, index) => {
215
227
  return `import error_${index} from '${error}';\n`;
216
228
  }).join('');
217
- const importLoaderComponentsCode = loaders.map((loader, index) => {
218
- return `import loader_${index} from '${dataLoaderPath}${loader}';\n`;
219
- }).join('');
229
+ let importLoadersCode = '';
230
+ if (loaders.length > 0) {
231
+ importLoadersCode = `
232
+ import { ${loaders.map((loader, index) => `loader_${index}`)} } from "${dataLoaderPath}${loadersIndexFile}"
233
+ `;
234
+ const loaderEntryCode = loaders.map((loader, index) => {
235
+ return `export * from './loader_${index}.js';`;
236
+ }).join('\n');
237
+ const loaderEntryFile = path.join(internalDirectory, entryName, TEMP_LOADERS_DIR, 'entry.js');
238
+ await fs.ensureFile(loaderEntryFile);
239
+ await fs.writeFile(loaderEntryFile, loaderEntryCode);
240
+ await fs.writeJSON(loadersMapFile, loadersMap);
241
+ await Promise.all(loaders.map(async (loader, index) => {
242
+ const name = `loader_${index}`;
243
+ const filename = path.join(internalDirectory, entryName, TEMP_LOADERS_DIR, `${name}.js`);
244
+ const code = `
245
+ export { loader as ${name} } from '${loader}'
246
+ `;
247
+ await fs.ensureFile(filename);
248
+ await fs.writeFile(filename, code);
249
+ }));
250
+ }
220
251
  return `
221
252
  ${importLazyCode}
253
+ ${rootLayoutCode}
222
254
  ${importLoadingCode}
223
255
  ${importErrorComponentsCode}
224
- ${importLoaderComponentsCode}
256
+ ${importLoadersCode}
225
257
  ${routeComponentsCode}
226
258
  `;
227
259
  };
@@ -1,7 +1,9 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
- import { isReact18, normalizeToPosixPath } from '@modern-js/utils';
4
- import { FILE_SYSTEM_ROUTES_FILE_NAME } from "./constants";
3
+ import { isReact18, normalizeToPosixPath, fs as fse } from '@modern-js/utils';
4
+ import { transform } from 'esbuild';
5
+ import { parse } from 'es-module-lexer';
6
+ import { FILE_SYSTEM_ROUTES_FILE_NAME, LOADER_EXPORT_NAME } from "./constants";
5
7
  export const walkDirectory = dir => fs.readdirSync(dir).reduce((previous, filename) => {
6
8
  const filePath = path.join(dir, filename);
7
9
  if (fs.statSync(filePath).isDirectory()) {
@@ -51,7 +53,7 @@ export const getDefaultImports = ({
51
53
  specifiers: [{
52
54
  imported: 'routes'
53
55
  }],
54
- value: normalizeToPosixPath(`${internalDirAlias}/${entryName}/${FILE_SYSTEM_ROUTES_FILE_NAME}`)
56
+ value: normalizeToPosixPath(`${internalDirAlias}/${entryName}/${FILE_SYSTEM_ROUTES_FILE_NAME.replace('.js', '')}`)
55
57
  };
56
58
  if (fileSystemRoutes.globalApp) {
57
59
  imports.push({
@@ -83,4 +85,28 @@ export const isRouteComponentFile = filePath => {
83
85
  }
84
86
  return false;
85
87
  };
86
- export const replaceWithAlias = (base, filePath, alias) => normalizeToPosixPath(path.join(alias, path.relative(base, filePath)));
88
+ export const replaceWithAlias = (base, filePath, alias) => normalizeToPosixPath(path.join(alias, path.relative(base, filePath)));
89
+ export const parseModule = async ({
90
+ source,
91
+ filename
92
+ }) => {
93
+ let content = source;
94
+ if (filename.endsWith('.tsx') || filename.endsWith('.jsx')) {
95
+ const result = await transform(content, {
96
+ loader: path.extname(filename).slice(1),
97
+ format: 'esm'
98
+ });
99
+ content = result.code;
100
+ }
101
+
102
+ // eslint-disable-next-line @typescript-eslint/await-thenable
103
+ return await parse(content);
104
+ };
105
+ export const hasLoader = async filename => {
106
+ const source = await fse.readFile(filename);
107
+ const [, moduleExports] = await parseModule({
108
+ source: source.toString(),
109
+ filename
110
+ });
111
+ return moduleExports.some(e => e.n === LOADER_EXPORT_NAME);
112
+ };
@@ -62,14 +62,15 @@ export const PluginCompatModern = (appContext, modernConfig, options) => ({
62
62
  }
63
63
 
64
64
  // apply copy plugin
65
- // const copyPatterns = createCopyPatterns(chain, appContext, modernConfig);
66
- const defaultCopyPattern = createCopyPattern(appContext, modernConfig, 'public', chain);
67
- chain.plugin(CHAIN_ID.PLUGIN.COPY).tap(args => {
68
- var _args$;
69
- return [{
70
- patterns: [...(((_args$ = args[0]) === null || _args$ === void 0 ? void 0 : _args$.patterns) || []), defaultCopyPattern]
71
- }];
72
- });
65
+ if (chain.plugins.has(CHAIN_ID.PLUGIN.COPY)) {
66
+ const defaultCopyPattern = createCopyPattern(appContext, modernConfig, 'public', chain);
67
+ chain.plugin(CHAIN_ID.PLUGIN.COPY).tap(args => {
68
+ var _args$;
69
+ return [{
70
+ patterns: [...(((_args$ = args[0]) === null || _args$ === void 0 ? void 0 : _args$.patterns) || []), defaultCopyPattern]
71
+ }];
72
+ });
73
+ }
73
74
  const {
74
75
  entrypoints
75
76
  } = appContext;
@@ -77,6 +78,11 @@ export const PluginCompatModern = (appContext, modernConfig, options) => ({
77
78
  chain.plugin('route-plugin').use(RouterPlugin, [{
78
79
  existNestedRoutes
79
80
  }]);
81
+ if (target !== 'node') {
82
+ const bareServerModuleReg = /\.(server|node)\.[tj]sx?$/;
83
+ chain.module.rule(CHAIN_ID.RULE.JS).exclude.add(bareServerModuleReg);
84
+ chain.module.rule('bare-server-module').test(bareServerModuleReg).use('server-module-loader').loader(require.resolve("../loaders/serverModuleLoader"));
85
+ }
80
86
  function isHtmlEnabled(config, target) {
81
87
  var _config$tools;
82
88
  return ((_config$tools = config.tools) === null || _config$tools === void 0 ? void 0 : _config$tools.htmlPlugin) !== false && target !== 'node' && target !== 'web-worker';
@@ -107,7 +113,7 @@ function applyCallbacks(api, options) {
107
113
  */
108
114
  function applyNodeCompat(chain, modernConfig, isProd) {
109
115
  // apply node resolve extensions
110
- for (const ext of ['.node.js', '.node.jsx', '.node.ts', '.node.tsx']) {
116
+ for (const ext of ['.node.js', '.node.jsx', '.node.ts', '.node.tsx', '.server.js', '.server.ts', '.server.ts', '.server.tsx']) {
111
117
  chain.resolve.extensions.prepend(ext);
112
118
  }
113
119
 
@@ -167,9 +173,9 @@ function applyBottomHtmlWebpackPlugin({
167
173
  // FIXME: the only need necessary
168
174
  const baseTemplateParams = _objectSpread({
169
175
  entryName,
170
- title: getEntryOptions(entryName, modernConfig.output.title, modernConfig.output.titleByEntries, appContext.packageName),
171
- mountId: modernConfig.output.mountId
172
- }, getEntryOptions(entryName, modernConfig.output.templateParameters, modernConfig.output.templateParametersByEntries, appContext.packageName));
176
+ title: getEntryOptions(entryName, modernConfig.html.title, modernConfig.html.titleByEntries, appContext.packageName),
177
+ mountId: modernConfig.html.mountId
178
+ }, getEntryOptions(entryName, modernConfig.html.templateParameters, modernConfig.html.templateParametersByEntries, appContext.packageName));
173
179
  chain.plugin(`${CHAIN_ID.PLUGIN.HTML}-${entryName}`).tap(args => [_objectSpread(_objectSpread({}, args[0] || {}), {}, {
174
180
  __internal__: true,
175
181
  bottomTemplate: appContext.htmlTemplates[`__${entryName}-bottom__`] && lodashTemplate(appContext.htmlTemplates[`__${entryName}-bottom__`])(baseTemplateParams)
@@ -1,11 +1,11 @@
1
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
3
+ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
1
4
  import { createBuilder } from '@modern-js/builder';
2
5
  import { builderWebpackProvider } from '@modern-js/builder-webpack-provider';
3
6
  import { applyOptionsChain, isUseSSRBundle } from '@modern-js/utils';
4
7
  import { PluginCompatModern } from "./builderPlugins/compatModern";
5
- import { createHtmlConfig } from "./createHtmlConfig";
6
- import { createOutputConfig } from "./createOutputConfig";
7
- import { createSourceConfig } from "./createSourceConfig";
8
- import { createToolsConfig } from "./createToolsConfig";
8
+ import { createCopyPattern } from "./share";
9
9
  function getBuilderTargets(normalizedConfig) {
10
10
  const targets = ['web'];
11
11
  if (normalizedConfig.output.enableModernMode && !targets.includes('modern-web')) {
@@ -21,8 +21,8 @@ export async function createBuilderForEdenX({
21
21
  appContext,
22
22
  compatPluginConfig
23
23
  }) {
24
- const builderConfig = createBuilderProviderConfig(normalizedConfig, appContext);
25
24
  // create webpack provider
25
+ const builderConfig = createBuilderProviderConfig(normalizedConfig, appContext);
26
26
  const webpackProvider = builderWebpackProvider({
27
27
  builderConfig
28
28
  });
@@ -32,25 +32,40 @@ export async function createBuilderForEdenX({
32
32
  await applyBuilderPlugins(builder, normalizedConfig, appContext, compatPluginConfig);
33
33
  return builder;
34
34
  }
35
- function createBuilderProviderConfig(normalizedConfig, appContext) {
36
- const source = createSourceConfig(normalizedConfig, appContext);
37
- const html = createHtmlConfig(normalizedConfig, appContext);
35
+ export function createBuilderProviderConfig(normalizedConfig, appContext) {
36
+ var _normalizedConfig$ser;
38
37
  const output = createOutputConfig(normalizedConfig, appContext);
39
- const tools = createToolsConfig(normalizedConfig);
40
- return {
41
- source,
42
- html,
38
+ return _objectSpread(_objectSpread({}, normalizedConfig), {}, {
39
+ source: _objectSpread(_objectSpread({}, normalizedConfig.source), {}, {
40
+ resolveExtensionPrefix: '.web'
41
+ }),
43
42
  output,
44
- tools,
45
43
  dev: {
44
+ port: (_normalizedConfig$ser = normalizedConfig.server) === null || _normalizedConfig$ser === void 0 ? void 0 : _normalizedConfig$ser.port,
46
45
  https: normalizedConfig.dev.https,
47
46
  assetPrefix: normalizedConfig.dev.assetPrefix
48
47
  },
49
- performance: {
48
+ html: _objectSpread(_objectSpread({}, normalizedConfig.html), {}, {
49
+ templateByEntries: normalizedConfig.html.templateByEntries || appContext.htmlTemplates
50
+ }),
51
+ performance: _objectSpread(_objectSpread({}, normalizedConfig.performance), {}, {
50
52
  // `@modern-js/webpack` used to remove moment locale by default
51
53
  removeMomentLocale: true
52
- }
53
- };
54
+ })
55
+ });
56
+ function createOutputConfig(config, appContext) {
57
+ const defaultCopyPattern = createCopyPattern(appContext, config, 'upload');
58
+ const {
59
+ copy
60
+ } = config.output;
61
+ const copyOptions = Array.isArray(copy) ? copy : copy === null || copy === void 0 ? void 0 : copy.patterns;
62
+ const builderCopy = [...(copyOptions || []), defaultCopyPattern];
63
+ return _objectSpread(_objectSpread({}, config.output), {}, {
64
+ copy: builderCopy,
65
+ // We need to do this in the app-tools prepare hook because some files will be generated into the dist directory in the analyze process
66
+ cleanDistPath: false
67
+ });
68
+ }
54
69
  }
55
70
  export function createBuilderOptions(target, appContext) {
56
71
  // create entries
@@ -0,0 +1,20 @@
1
+ function loader(source) {
2
+ // eslint-disable-next-line @babel/no-invalid-this
3
+ this.cacheable();
4
+ // eslint-disable-next-line @babel/no-invalid-this
5
+ const {
6
+ target
7
+ } = this._compiler.options;
8
+ if (target === 'node' || Array.isArray(target) && target.includes('node')) {
9
+ return source;
10
+ }
11
+ // eslint-disable-next-line @babel/no-invalid-this
12
+ const {
13
+ resourcePath
14
+ } = this;
15
+ const code = `
16
+ export { default } from "${resourcePath}";
17
+ `;
18
+ return code;
19
+ }
20
+ export default loader;
@@ -0,0 +1,4 @@
1
+ function loader() {
2
+ return `module.exports = {}`;
3
+ }
4
+ export default loader;
@@ -2,7 +2,7 @@ import path from 'path';
2
2
  import { template as lodashTemplate } from '@modern-js/utils/lodash';
3
3
  import { removeTailSlash } from '@modern-js/utils';
4
4
  export function createCopyPattern(appContext, config, patternsType, chain) {
5
- const configDir = path.resolve(appContext.appDirectory, config.source.configDir);
5
+ const configDir = path.resolve(appContext.appDirectory, config.source.configDir || './config');
6
6
  const uploadDir = path.posix.join(configDir.replace(/\\/g, '/'), 'upload');
7
7
  const publicDir = path.posix.join(configDir.replace(/\\/g, '/'), 'public');
8
8
  const minifiedJsRexExp = /\.min\.js/;
@@ -6,6 +6,10 @@ import { logger, printBuildError } from '@modern-js/utils';
6
6
  import { generateRoutes } from "../utils/routes";
7
7
  import { buildServerConfig } from "../utils/config";
8
8
  export const build = async (api, options) => {
9
+ if (options !== null && options !== void 0 && options.analyze) {
10
+ // Builder will read this env var to enable bundle analyzer
11
+ process.env.BUNDLE_ANALYZE = 'true';
12
+ }
9
13
  let resolvedConfig = api.useResolvedConfigContext();
10
14
  const appContext = api.useAppContext();
11
15
  const hookRunners = api.useHookRunners();
@@ -49,9 +53,11 @@ export const build = async (api, options) => {
49
53
  configFile: serverConfigFile
50
54
  });
51
55
  try {
52
- var _appContext$builder;
53
56
  logger.info('Create a production build...\n');
54
- await ((_appContext$builder = appContext.builder) === null || _appContext$builder === void 0 ? void 0 : _appContext$builder.build());
57
+ if (!appContext.builder) {
58
+ throw new Error('Expect the Builder to have been initialized, But the appContext.builder received `undefined`');
59
+ }
60
+ await appContext.builder.build();
55
61
  } catch (error) {
56
62
  printBuildError(error);
57
63
  // eslint-disable-next-line no-process-exit
@@ -1,21 +1,26 @@
1
1
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2
2
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
3
3
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
4
- import { logger } from '@modern-js/utils';
5
4
  import { ResolvedConfigContext } from '@modern-js/core';
5
+ import { createFileWatcher } from "../utils/createFileWatcher";
6
6
  import { printInstructions } from "../utils/printInstructions";
7
7
  import { createServer, injectDataLoaderPlugin } from "../utils/createServer";
8
8
  import { generateRoutes } from "../utils/routes";
9
9
  import { getSpecifiedEntries } from "../utils/getSpecifiedEntries";
10
10
  import { buildServerConfig } from "../utils/config";
11
11
  export const dev = async (api, options) => {
12
- let userConfig = api.useResolvedConfigContext();
12
+ var _normalizedConfig$too;
13
+ if (options.analyze) {
14
+ // Builder will read this env var to enable bundle analyzer
15
+ process.env.BUNDLE_ANALYZE = 'true';
16
+ }
17
+ let normalizedConfig = api.useResolvedConfigContext();
13
18
  const appContext = api.useAppContext();
14
19
  const hookRunners = api.useHookRunners();
15
- userConfig = _objectSpread(_objectSpread({}, userConfig), {}, {
20
+ normalizedConfig = _objectSpread(_objectSpread({}, normalizedConfig), {}, {
16
21
  cliOptions: options
17
22
  });
18
- ResolvedConfigContext.set(userConfig);
23
+ ResolvedConfigContext.set(normalizedConfig);
19
24
  const {
20
25
  appDirectory,
21
26
  distDirectory,
@@ -41,39 +46,39 @@ export const dev = async (api, options) => {
41
46
  }
42
47
  });
43
48
  await hookRunners.beforeDev();
44
- let compiler = null;
49
+ let compiler;
50
+ if (!appContext.builder && !apiOnly) {
51
+ throw new Error('Expect the Builder to have been initialized, But the appContext.builder received `undefined`');
52
+ }
45
53
  if (!apiOnly) {
46
- var _appContext$builder;
47
- compiler = await ((_appContext$builder = appContext.builder) === null || _appContext$builder === void 0 ? void 0 : _appContext$builder.createCompiler());
54
+ compiler = await appContext.builder.createCompiler();
48
55
  }
49
56
  await generateRoutes(appContext);
50
- const app = await createServer({
51
- dev: _objectSpread(_objectSpread({}, {
52
- client: {
53
- port: port.toString()
54
- },
55
- devMiddleware: {
56
- writeToDisk: file => !file.includes('.hot-update.')
57
- },
58
- hot: true,
59
- liveReload: true,
57
+ const serverOptions = {
58
+ dev: _objectSpread({
60
59
  port,
61
- https: userConfig.dev.https
62
- }), userConfig.tools.devServer),
63
- compiler,
60
+ https: normalizedConfig.dev.https
61
+ }, (_normalizedConfig$too = normalizedConfig.tools) === null || _normalizedConfig$too === void 0 ? void 0 : _normalizedConfig$too.devServer),
62
+ compiler: compiler || null,
64
63
  pwd: appDirectory,
65
- config: userConfig,
64
+ config: normalizedConfig,
66
65
  serverConfigFile,
67
66
  internalPlugins: injectDataLoaderPlugin(serverInternalPlugins)
68
- });
69
- app.listen(port, async err => {
70
- if (err) {
71
- throw err;
72
- }
73
- if (!apiOnly) {
74
- logger.info(`Starting dev server...\n`);
75
- } else {
76
- printInstructions(hookRunners, appContext, userConfig);
77
- }
78
- });
67
+ };
68
+ if (apiOnly) {
69
+ const app = await createServer(serverOptions);
70
+ app.listen(port, async err => {
71
+ if (err) {
72
+ throw err;
73
+ }
74
+ printInstructions(hookRunners, appContext, normalizedConfig);
75
+ });
76
+ } else {
77
+ await appContext.builder.startDevServer({
78
+ compiler,
79
+ printURLs: false,
80
+ serverOptions
81
+ });
82
+ }
83
+ await createFileWatcher(appContext, normalizedConfig.source.configDir, hookRunners);
79
84
  };
@@ -1,8 +1,10 @@
1
1
  import { join } from 'path';
2
2
  export const inspect = async (api, options) => {
3
- var _appContext$builder;
4
3
  const appContext = api.useAppContext();
5
- return (_appContext$builder = appContext.builder) === null || _appContext$builder === void 0 ? void 0 : _appContext$builder.inspectConfig({
4
+ if (!appContext.builder) {
5
+ throw new Error('Expect the Builder to have been initialized, But the appContext.builder received `undefined`');
6
+ }
7
+ return appContext.builder.inspectConfig({
6
8
  env: options.env,
7
9
  verbose: options.verbose,
8
10
  outputPath: join(appContext === null || appContext === void 0 ? void 0 : appContext.builder.context.distPath, options.output),