@modern-js/app-tools 1.21.5 → 2.0.0-beta.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.
Files changed (170) hide show
  1. package/CHANGELOG.md +319 -51
  2. package/dist/js/modern/analyze/constants.js +1 -0
  3. package/dist/js/modern/analyze/generateCode.js +126 -32
  4. package/dist/js/modern/analyze/getBundleEntry.js +7 -14
  5. package/dist/js/modern/analyze/getClientRoutes/getRoutes.js +173 -0
  6. package/dist/js/modern/analyze/{getClientRoutes.js → getClientRoutes/getRoutesLegacy.js} +13 -58
  7. package/dist/js/modern/analyze/getClientRoutes/index.js +2 -0
  8. package/dist/js/modern/analyze/getClientRoutes/utils.js +18 -0
  9. package/dist/js/modern/analyze/getFileSystemEntry.js +27 -21
  10. package/dist/js/modern/analyze/getHtmlTemplate.js +2 -9
  11. package/dist/js/modern/analyze/getServerRoutes.js +15 -32
  12. package/dist/js/modern/analyze/index.js +81 -23
  13. package/dist/js/modern/analyze/isDefaultExportFunction.js +0 -4
  14. package/dist/js/modern/analyze/makeLegalIdentifier.js +0 -2
  15. package/dist/js/modern/analyze/nestedRoutes.js +102 -0
  16. package/dist/js/modern/analyze/templates.js +151 -12
  17. package/dist/js/modern/analyze/utils.js +2 -8
  18. package/dist/js/modern/builder/builderPlugins/compatModern.js +208 -0
  19. package/dist/js/modern/builder/createHtmlConfig.js +58 -0
  20. package/dist/js/modern/builder/createOutputConfig.js +70 -0
  21. package/dist/js/modern/builder/createSourceConfig.js +74 -0
  22. package/dist/js/modern/builder/createToolsConfig.js +87 -0
  23. package/dist/js/modern/builder/index.js +108 -0
  24. package/dist/js/modern/builder/share.js +44 -0
  25. package/dist/js/modern/builder/webpackPlugins/htmlAsyncChunkPlugin.js +29 -0
  26. package/dist/js/modern/builder/webpackPlugins/htmlBottomTemplate.js +33 -0
  27. package/dist/js/modern/builder/webpackPlugins/routerPlugin.js +97 -0
  28. package/dist/js/modern/commands/build.js +16 -110
  29. package/dist/js/modern/commands/dev.js +12 -28
  30. package/dist/js/modern/commands/inspect.js +8 -66
  31. package/dist/js/modern/commands/start.js +2 -3
  32. package/dist/js/modern/index.js +17 -16
  33. package/dist/js/modern/locale/en.js +0 -1
  34. package/dist/js/modern/locale/zh.js +0 -1
  35. package/dist/js/modern/utils/commands.js +5 -0
  36. package/dist/js/modern/utils/config.js +1 -12
  37. package/dist/js/modern/utils/createServer.js +12 -1
  38. package/dist/js/modern/utils/getSpecifiedEntries.js +0 -6
  39. package/dist/js/modern/utils/printInstructions.js +3 -2
  40. package/dist/js/modern/utils/routes.js +0 -2
  41. package/dist/js/node/analyze/constants.js +3 -1
  42. package/dist/js/node/analyze/generateCode.js +123 -47
  43. package/dist/js/node/analyze/getBundleEntry.js +7 -20
  44. package/dist/js/node/analyze/getClientRoutes/getRoutes.js +181 -0
  45. package/dist/js/node/analyze/{getClientRoutes.js → getClientRoutes/getRoutesLegacy.js} +19 -78
  46. package/dist/js/node/analyze/getClientRoutes/index.js +19 -0
  47. package/dist/js/node/analyze/getClientRoutes/utils.js +28 -0
  48. package/dist/js/node/analyze/getFileSystemEntry.js +26 -28
  49. package/dist/js/node/analyze/getHtmlTemplate.js +2 -23
  50. package/dist/js/node/analyze/getServerRoutes.js +14 -40
  51. package/dist/js/node/analyze/index.js +81 -33
  52. package/dist/js/node/analyze/isDefaultExportFunction.js +0 -12
  53. package/dist/js/node/analyze/makeLegalIdentifier.js +0 -4
  54. package/dist/js/node/analyze/nestedRoutes.js +111 -0
  55. package/dist/js/node/analyze/templates.js +153 -21
  56. package/dist/js/node/analyze/utils.js +4 -20
  57. package/dist/js/node/builder/builderPlugins/compatModern.js +216 -0
  58. package/dist/js/node/builder/createHtmlConfig.js +68 -0
  59. package/dist/js/node/builder/createOutputConfig.js +76 -0
  60. package/dist/js/node/builder/createSourceConfig.js +82 -0
  61. package/dist/js/node/builder/createToolsConfig.js +94 -0
  62. package/dist/js/node/builder/index.js +117 -0
  63. package/dist/js/node/builder/share.js +51 -0
  64. package/dist/js/node/builder/webpackPlugins/htmlAsyncChunkPlugin.js +36 -0
  65. package/dist/js/node/builder/webpackPlugins/htmlBottomTemplate.js +40 -0
  66. package/dist/js/node/builder/webpackPlugins/routerPlugin.js +105 -0
  67. package/dist/js/node/commands/build.js +14 -121
  68. package/dist/js/node/commands/deploy.js +0 -2
  69. package/dist/js/node/commands/dev.js +10 -44
  70. package/dist/js/node/commands/index.js +0 -6
  71. package/dist/js/node/commands/inspect.js +10 -90
  72. package/dist/js/node/commands/start.js +2 -11
  73. package/dist/js/node/exports/server.js +0 -1
  74. package/dist/js/node/hooks.js +0 -2
  75. package/dist/js/node/index.js +22 -32
  76. package/dist/js/node/locale/en.js +0 -1
  77. package/dist/js/node/locale/index.js +0 -4
  78. package/dist/js/node/locale/zh.js +0 -1
  79. package/dist/js/node/utils/commands.js +12 -0
  80. package/dist/js/node/utils/config.js +1 -25
  81. package/dist/js/node/utils/createServer.js +15 -11
  82. package/dist/js/node/utils/getSpecifiedEntries.js +0 -9
  83. package/dist/js/node/utils/language.js +0 -2
  84. package/dist/js/node/utils/printInstructions.js +3 -6
  85. package/dist/js/node/utils/routes.js +0 -5
  86. package/dist/js/treeshaking/analyze/constants.js +16 -0
  87. package/dist/js/treeshaking/analyze/generateCode.js +369 -0
  88. package/dist/js/treeshaking/analyze/getBundleEntry.js +69 -0
  89. package/dist/js/treeshaking/analyze/getClientRoutes/getRoutes.js +184 -0
  90. package/dist/js/treeshaking/analyze/getClientRoutes/getRoutesLegacy.js +185 -0
  91. package/dist/js/treeshaking/analyze/getClientRoutes/index.js +2 -0
  92. package/dist/js/treeshaking/analyze/getClientRoutes/utils.js +24 -0
  93. package/dist/js/treeshaking/analyze/getFileSystemEntry.js +96 -0
  94. package/dist/js/treeshaking/analyze/getHtmlTemplate.js +129 -0
  95. package/dist/js/treeshaking/analyze/getServerRoutes.js +157 -0
  96. package/dist/js/treeshaking/analyze/index.js +334 -0
  97. package/dist/js/treeshaking/analyze/isDefaultExportFunction.js +28 -0
  98. package/dist/js/treeshaking/analyze/makeLegalIdentifier.js +16 -0
  99. package/dist/js/treeshaking/analyze/nestedRoutes.js +165 -0
  100. package/dist/js/treeshaking/analyze/templates.js +170 -0
  101. package/dist/js/treeshaking/analyze/utils.js +88 -0
  102. package/dist/js/treeshaking/builder/builderPlugins/compatModern.js +212 -0
  103. package/dist/js/treeshaking/builder/createHtmlConfig.js +59 -0
  104. package/dist/js/treeshaking/builder/createOutputConfig.js +70 -0
  105. package/dist/js/treeshaking/builder/createSourceConfig.js +88 -0
  106. package/dist/js/treeshaking/builder/createToolsConfig.js +85 -0
  107. package/dist/js/treeshaking/builder/index.js +161 -0
  108. package/dist/js/treeshaking/builder/share.js +46 -0
  109. package/dist/js/treeshaking/builder/webpackPlugins/htmlAsyncChunkPlugin.js +46 -0
  110. package/dist/js/treeshaking/builder/webpackPlugins/htmlBottomTemplate.js +41 -0
  111. package/dist/js/treeshaking/builder/webpackPlugins/routerPlugin.js +121 -0
  112. package/dist/js/treeshaking/commands/build.js +83 -0
  113. package/dist/js/treeshaking/commands/deploy.js +26 -0
  114. package/dist/js/treeshaking/commands/dev.js +124 -0
  115. package/dist/js/treeshaking/commands/index.js +3 -0
  116. package/dist/js/treeshaking/commands/inspect.js +29 -0
  117. package/dist/js/treeshaking/commands/start.js +69 -0
  118. package/dist/js/treeshaking/exports/server.js +1 -0
  119. package/dist/js/treeshaking/hooks.js +21 -0
  120. package/dist/js/treeshaking/index.js +267 -0
  121. package/dist/js/treeshaking/locale/en.js +34 -0
  122. package/dist/js/treeshaking/locale/index.js +9 -0
  123. package/dist/js/treeshaking/locale/zh.js +34 -0
  124. package/dist/js/treeshaking/utils/commands.js +5 -0
  125. package/dist/js/treeshaking/utils/config.js +124 -0
  126. package/dist/js/treeshaking/utils/createServer.js +73 -0
  127. package/dist/js/treeshaking/utils/getSpecifiedEntries.js +58 -0
  128. package/dist/js/treeshaking/utils/language.js +5 -0
  129. package/dist/js/treeshaking/utils/printInstructions.js +30 -0
  130. package/dist/js/treeshaking/utils/routes.js +29 -0
  131. package/dist/js/treeshaking/utils/types.js +0 -0
  132. package/dist/types/analyze/constants.d.ts +1 -0
  133. package/dist/types/analyze/generateCode.d.ts +1 -1
  134. package/dist/types/analyze/{getClientRoutes.d.ts → getClientRoutes/getRoutes.d.ts} +2 -7
  135. package/dist/types/analyze/getClientRoutes/getRoutesLegacy.d.ts +15 -0
  136. package/dist/types/analyze/getClientRoutes/index.d.ts +2 -0
  137. package/dist/types/analyze/getClientRoutes/utils.d.ts +5 -0
  138. package/dist/types/analyze/index.d.ts +4 -5
  139. package/dist/types/analyze/nestedRoutes.d.ts +5 -0
  140. package/dist/types/analyze/templates.d.ts +19 -3
  141. package/dist/types/analyze/utils.d.ts +2 -1
  142. package/dist/types/builder/builderPlugins/compatModern.d.ts +13 -0
  143. package/dist/types/builder/createHtmlConfig.d.ts +6 -0
  144. package/dist/types/builder/createOutputConfig.d.ts +3 -0
  145. package/dist/types/builder/createSourceConfig.d.ts +5 -0
  146. package/dist/types/builder/createToolsConfig.d.ts +13 -0
  147. package/dist/types/builder/index.d.ts +15 -0
  148. package/dist/types/builder/share.d.ts +26 -0
  149. package/dist/types/builder/webpackPlugins/htmlAsyncChunkPlugin.d.ts +8 -0
  150. package/dist/types/builder/webpackPlugins/htmlBottomTemplate.d.ts +10 -0
  151. package/dist/types/builder/webpackPlugins/routerPlugin.d.ts +10 -0
  152. package/dist/types/commands/build.d.ts +2 -1
  153. package/dist/types/commands/deploy.d.ts +2 -1
  154. package/dist/types/commands/dev.d.ts +2 -1
  155. package/dist/types/commands/inspect.d.ts +2 -6
  156. package/dist/types/commands/start.d.ts +2 -1
  157. package/dist/types/hooks.d.ts +15 -10
  158. package/dist/types/index.d.ts +4 -4
  159. package/dist/types/locale/en.d.ts +0 -1
  160. package/dist/types/locale/index.d.ts +0 -2
  161. package/dist/types/locale/zh.d.ts +0 -1
  162. package/dist/types/utils/commands.d.ts +1 -0
  163. package/dist/types/utils/config.d.ts +0 -1
  164. package/dist/types/utils/createServer.d.ts +8 -1
  165. package/dist/types/utils/printInstructions.d.ts +3 -2
  166. package/dist/types/utils/types.d.ts +2 -3
  167. package/package.json +25 -42
  168. package/dist/js/modern/utils/createCompiler.js +0 -61
  169. package/dist/js/node/utils/createCompiler.js +0 -81
  170. package/dist/types/utils/createCompiler.d.ts +0 -13
@@ -0,0 +1,44 @@
1
+ import path from 'path';
2
+ import { template as lodashTemplate } from '@modern-js/utils/lodash';
3
+ import { removeTailSlash } from '@modern-js/utils';
4
+ export function createCopyPattern(appContext, config, patternsType, chain) {
5
+ const configDir = path.resolve(appContext.appDirectory, config.source.configDir);
6
+ const uploadDir = path.posix.join(configDir.replace(/\\/g, '/'), 'upload');
7
+ const publicDir = path.posix.join(configDir.replace(/\\/g, '/'), 'public');
8
+ const minifiedJsRexExp = /\.min\.js/;
9
+ const info = file => ({
10
+ // If the file name ends with `.min.js`, we assume it's a compressed file.
11
+ // So we don't want copy-webpack-plugin to minify it.
12
+ // ref: https://github.com/webpack-contrib/copy-webpack-plugin#info
13
+ minimized: minifiedJsRexExp.test(file.sourceFilename)
14
+ });
15
+ if (patternsType === 'public') {
16
+ if (!chain) {
17
+ throw new Error("expect get a webpackChain, but receive 'undefined'");
18
+ }
19
+ return {
20
+ info,
21
+ from: '**/*',
22
+ to: 'public',
23
+ context: publicDir,
24
+ noErrorOnMissing: true,
25
+ // eslint-disable-next-line node/prefer-global/buffer
26
+ transform: (content, absoluteFrom) => {
27
+ if (!/\.html?$/.test(absoluteFrom)) {
28
+ return content;
29
+ }
30
+ return lodashTemplate(content.toString('utf8'))({
31
+ assetPrefix: removeTailSlash(chain.output.get('publicPath'))
32
+ });
33
+ }
34
+ };
35
+ } else {
36
+ return {
37
+ info,
38
+ from: '**/*',
39
+ to: 'upload',
40
+ context: uploadDir,
41
+ noErrorOnMissing: true
42
+ };
43
+ }
44
+ }
@@ -0,0 +1,29 @@
1
+ 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; }
2
+ export class HtmlAsyncChunkPlugin {
3
+ constructor(htmlWebpackPlugin) {
4
+ _defineProperty(this, "name", void 0);
5
+ _defineProperty(this, "htmlWebpackPlugin", void 0);
6
+ this.name = 'HtmlAsyncChunkPlugin';
7
+ this.htmlWebpackPlugin = htmlWebpackPlugin;
8
+ }
9
+ apply(compiler) {
10
+ compiler.hooks.compilation.tap(this.name, compilation => {
11
+ const hooks = this.htmlWebpackPlugin.getHooks(compilation);
12
+ hooks.alterAssetTagGroups.tap(this.name, assets => {
13
+ const tags = [...assets.headTags, ...assets.bodyTags];
14
+ for (const tag of tags) {
15
+ if (tag.tagName === 'script') {
16
+ const {
17
+ attributes
18
+ } = tag;
19
+ if (attributes && attributes.defer === true) {
20
+ attributes.async = true;
21
+ delete attributes.defer;
22
+ }
23
+ }
24
+ }
25
+ return assets;
26
+ });
27
+ });
28
+ }
29
+ }
@@ -0,0 +1,33 @@
1
+ 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; }
2
+ export class BottomTemplatePlugin {
3
+ constructor(htmlWebpackPlugin) {
4
+ _defineProperty(this, "htmlWebpackPlugin", void 0);
5
+ _defineProperty(this, "bottomTemplateReg", /<!--<\?-\s*bottomTemplate\s*\?>-->/);
6
+ _defineProperty(this, "bodyRegExp", /(<\/\s*body\s*>)/i);
7
+ _defineProperty(this, "name", void 0);
8
+ this.htmlWebpackPlugin = htmlWebpackPlugin;
9
+ this.name = 'bottom-template';
10
+ }
11
+ apply(compiler) {
12
+ compiler.hooks.compilation.tap(this.name, compilation => {
13
+ this.htmlWebpackPlugin.getHooks(compilation).beforeEmit.tap(this.name, data => {
14
+ var _data$plugin$options;
15
+ if (!((_data$plugin$options = data.plugin.options) !== null && _data$plugin$options !== void 0 && _data$plugin$options.__internal__)) {
16
+ return data;
17
+ }
18
+ // 含有 <!--<?- bottomTemplate ?>--> 占位符时才需要注入 bottom.html
19
+ if (this.bottomTemplateReg.test(data.html)) {
20
+ // 清空占位符
21
+ data.html = data.html.replace(this.bottomTemplateReg, '');
22
+ const {
23
+ bottomTemplate
24
+ } = data.plugin.options;
25
+ if (bottomTemplate) {
26
+ data.html = data.html.replace(this.bodyRegExp, match => `\n${bottomTemplate}\n${match}`);
27
+ }
28
+ }
29
+ return data;
30
+ });
31
+ });
32
+ }
33
+ }
@@ -0,0 +1,97 @@
1
+ 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; }
2
+ import path from 'path';
3
+ import { fs, ROUTE_MANIFEST, logger, ROUTE_MINIFEST_FILE } from '@modern-js/utils';
4
+ const PLUGIN_NAME = 'ModernjsRoutePlugin';
5
+ export default class RouterPlugin {
6
+ constructor(options) {
7
+ _defineProperty(this, "existNestedRoutes", void 0);
8
+ this.existNestedRoutes = options.existNestedRoutes;
9
+ }
10
+ apply(compiler) {
11
+ const {
12
+ existNestedRoutes
13
+ } = this;
14
+ const {
15
+ target
16
+ } = compiler.options;
17
+ if (target === 'node' || Array.isArray(target) && target.includes('node')) {
18
+ return;
19
+ }
20
+ if (!existNestedRoutes) {
21
+ return;
22
+ }
23
+ const {
24
+ webpack
25
+ } = compiler;
26
+ const {
27
+ Compilation,
28
+ sources
29
+ } = webpack;
30
+ const {
31
+ RawSource
32
+ } = sources;
33
+ const {
34
+ PROCESS_ASSETS_STAGE_REPORT
35
+ } = Compilation;
36
+ const outputPath = compiler.options.output.path;
37
+ const newAssetsMap = new Map();
38
+ const normalizePath = path => {
39
+ if (!path.endsWith('/')) {
40
+ return `${path}/`;
41
+ }
42
+ return path;
43
+ };
44
+ compiler.hooks.thisCompilation.tap(PLUGIN_NAME, compilation => {
45
+ compilation.hooks.processAssets.tapPromise({
46
+ name: PLUGIN_NAME,
47
+ stage: PROCESS_ASSETS_STAGE_REPORT
48
+ }, async () => {
49
+ const stats = compilation.getStats().toJson({
50
+ chunkGroups: true,
51
+ chunks: true
52
+ });
53
+ const {
54
+ publicPath
55
+ } = stats;
56
+ const routeAssets = {};
57
+ const {
58
+ namedChunkGroups,
59
+ assetsByChunkName
60
+ } = stats;
61
+ if (!namedChunkGroups || !assetsByChunkName) {
62
+ logger.warn('Route manifest does not exist, performance will be affected');
63
+ return;
64
+ }
65
+ for (const [name, chunkGroup] of Object.entries(namedChunkGroups)) {
66
+ routeAssets[name] = {
67
+ chunkIds: chunkGroup.chunks,
68
+ assets: assetsByChunkName[name].map(item => publicPath ? normalizePath(publicPath) + item : item)
69
+ };
70
+ }
71
+ const manifest = {
72
+ routeAssets
73
+ };
74
+ const injectedContent = `
75
+ ;(function(){
76
+ window.${ROUTE_MANIFEST} = ${JSON.stringify(manifest)};
77
+ })();
78
+ `;
79
+ const entrypointsArray = Array.from(compilation.entrypoints.entries());
80
+ const entryChunkIds = entrypointsArray.map(entrypoint => entrypoint[0]);
81
+ const entryChunks = [...compilation.chunks].filter(chunk => {
82
+ return entryChunkIds.includes(chunk.name);
83
+ });
84
+ const entryChunkFiles = entryChunks.map(chunk => [...chunk.files][0]);
85
+ for (const file of entryChunkFiles) {
86
+ const asset = compilation.assets[file];
87
+ const newContent = `${injectedContent}${asset.source().toString()}`;
88
+ newAssetsMap.set(path.join(outputPath, file), newContent);
89
+ compilation.updateAsset(file, new RawSource(newContent));
90
+ }
91
+ const filename = path.join(outputPath, ROUTE_MINIFEST_FILE);
92
+ await fs.ensureFile(filename);
93
+ await fs.writeFile(filename, JSON.stringify(manifest, null, 2));
94
+ });
95
+ });
96
+ }
97
+ }
@@ -1,17 +1,10 @@
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
-
3
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; }
4
-
5
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; }
6
-
7
- import { webpack, getWebpackConfig, WebpackConfigTarget } from '@modern-js/webpack';
8
4
  import { ResolvedConfigContext } from '@modern-js/core';
9
- import { formatWebpackMessages, measureFileSizesBeforeBuild, printFileSizesAfterBuild, printBuildError, logger, isUseSSRBundle, emptyDir } from '@modern-js/utils';
5
+ import { logger, printBuildError } from '@modern-js/utils';
10
6
  import { generateRoutes } from "../utils/routes";
11
- import { buildServerConfig, emitResolvedConfig } from "../utils/config";
12
- // These sizes are pretty large. We'll warn for bundles exceeding them.
13
- const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
14
- const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;
7
+ import { buildServerConfig } from "../utils/config";
15
8
  export const build = async (api, options) => {
16
9
  let resolvedConfig = api.useResolvedConfigContext();
17
10
  const appContext = api.useAppContext();
@@ -19,16 +12,15 @@ export const build = async (api, options) => {
19
12
  const {
20
13
  apiOnly
21
14
  } = appContext;
22
-
23
15
  if (apiOnly) {
24
16
  const {
25
17
  appDirectory,
26
18
  distDirectory,
27
19
  serverConfigFile
28
20
  } = appContext;
29
- await emptyDir(distDirectory);
30
21
  await hookRunners.beforeBuild({
31
- webpackConfigs: []
22
+ // "null" bundlerConfigs
23
+ bundlerConfigs: undefined
32
24
  });
33
25
  await buildServerConfig({
34
26
  appDirectory,
@@ -36,61 +28,12 @@ export const build = async (api, options) => {
36
28
  configFile: serverConfigFile
37
29
  });
38
30
  await generateRoutes(appContext);
39
- await hookRunners.afterBuild();
31
+ await hookRunners.afterBuild({
32
+ // "null" stats
33
+ stats: undefined
34
+ });
40
35
  return;
41
36
  }
42
-
43
- const webpackBuild = async (webpackConfig, type) => {
44
- const compiler = webpack(webpackConfig);
45
- return new Promise((resolve, reject) => {
46
- let label = process.env.NODE_ENV || '';
47
-
48
- if (type && type !== 'legacy') {
49
- label += ` ${type}`;
50
- }
51
-
52
- logger.info(`Creating a ${label} build...`);
53
- compiler.run((err, stats) => {
54
- let messages;
55
-
56
- if (!err) {
57
- messages = formatWebpackMessages(stats.toJson({
58
- all: false,
59
- warnings: true,
60
- errors: true
61
- }));
62
-
63
- if (messages.errors.length === 0) {
64
- logger.info(`File sizes after ${label} build:\n`);
65
- printFileSizesAfterBuild(stats, previousFileSizes, distDirectory, WARN_AFTER_BUNDLE_GZIP_SIZE, WARN_AFTER_CHUNK_GZIP_SIZE);
66
- logger.log();
67
- }
68
- } // When using run or watch, call close and wait for it to finish before calling run or watch again.
69
- // Concurrent compilations will corrupt the output files.
70
-
71
-
72
- compiler.close(closeErr => {
73
- if (closeErr) {
74
- logger.error(closeErr);
75
- }
76
-
77
- if (err) {
78
- reject(err);
79
- } else {
80
- if (messages.errors.length) {
81
- reject(new Error(messages.errors.join('\n\n')));
82
- return;
83
- }
84
-
85
- resolve({
86
- warnings: messages.warnings
87
- });
88
- }
89
- });
90
- });
91
- });
92
- };
93
-
94
37
  resolvedConfig = _objectSpread(_objectSpread({}, resolvedConfig), {}, {
95
38
  cliOptions: options
96
39
  });
@@ -100,55 +43,18 @@ export const build = async (api, options) => {
100
43
  appDirectory,
101
44
  serverConfigFile
102
45
  } = appContext;
103
- const previousFileSizes = await measureFileSizesBeforeBuild(distDirectory);
104
- await emptyDir(distDirectory);
105
46
  await buildServerConfig({
106
47
  appDirectory,
107
48
  distDirectory,
108
49
  configFile: serverConfigFile
109
50
  });
110
- const buildConfigs = [];
111
- buildConfigs.push({
112
- type: 'legacy',
113
- config: getWebpackConfig(WebpackConfigTarget.CLIENT, appContext, resolvedConfig)
114
- });
115
-
116
- if (resolvedConfig.output.enableModernMode) {
117
- buildConfigs.push({
118
- type: 'modern',
119
- config: getWebpackConfig(WebpackConfigTarget.MODERN, appContext, resolvedConfig)
120
- });
121
- }
122
-
123
- if (isUseSSRBundle(resolvedConfig)) {
124
- buildConfigs.push({
125
- type: 'ssr',
126
- config: getWebpackConfig(WebpackConfigTarget.NODE, appContext, resolvedConfig)
127
- });
128
- }
129
-
130
- await hookRunners.beforeBuild({
131
- webpackConfigs: buildConfigs.map(({
132
- config
133
- }) => config)
134
- });
135
-
136
- for (const buildConfig of buildConfigs) {
137
- const {
138
- type: buildType,
139
- config
140
- } = buildConfig;
141
-
142
- try {
143
- await webpackBuild(config, buildType);
144
- } catch (error) {
145
- printBuildError(error); // eslint-disable-next-line no-process-exit
146
-
147
- process.exit(1);
148
- }
51
+ try {
52
+ var _appContext$builder;
53
+ logger.info('Create a production build...\n');
54
+ await ((_appContext$builder = appContext.builder) === null || _appContext$builder === void 0 ? void 0 : _appContext$builder.build());
55
+ } catch (error) {
56
+ printBuildError(error);
57
+ // eslint-disable-next-line no-process-exit
58
+ process.exit(1);
149
59
  }
150
-
151
- await generateRoutes(appContext);
152
- await hookRunners.afterBuild();
153
- await emitResolvedConfig(appDirectory, resolvedConfig);
154
60
  };
@@ -1,15 +1,11 @@
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
-
3
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; }
4
-
5
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; }
6
-
7
- import { fs, logger, chalk, isSSR } from '@modern-js/utils';
4
+ import { logger } from '@modern-js/utils';
8
5
  import { ResolvedConfigContext } from '@modern-js/core';
9
- import { createCompiler } from "../utils/createCompiler";
10
- import { createServer } from "../utils/createServer";
11
- import { generateRoutes } from "../utils/routes";
12
6
  import { printInstructions } from "../utils/printInstructions";
7
+ import { createServer, injectDataLoaderPlugin } from "../utils/createServer";
8
+ import { generateRoutes } from "../utils/routes";
13
9
  import { getSpecifiedEntries } from "../utils/getSpecifiedEntries";
14
10
  import { buildServerConfig } from "../utils/config";
15
11
  export const dev = async (api, options) => {
@@ -26,14 +22,14 @@ export const dev = async (api, options) => {
26
22
  port,
27
23
  apiOnly,
28
24
  entrypoints,
29
- serverConfigFile
25
+ serverConfigFile,
26
+ serverInternalPlugins
30
27
  } = appContext;
31
28
  const checkedEntries = await getSpecifiedEntries(options.entry || false, entrypoints);
32
29
  api.setAppContext(_objectSpread(_objectSpread({}, appContext), {}, {
33
30
  checkedEntries
34
31
  }));
35
32
  appContext.checkedEntries = checkedEntries;
36
- fs.emptyDirSync(distDirectory);
37
33
  await buildServerConfig({
38
34
  appDirectory,
39
35
  distDirectory,
@@ -46,21 +42,10 @@ export const dev = async (api, options) => {
46
42
  });
47
43
  await hookRunners.beforeDev();
48
44
  let compiler = null;
49
-
50
45
  if (!apiOnly) {
51
- const {
52
- getWebpackConfig,
53
- WebpackConfigTarget
54
- } = await import('@modern-js/webpack');
55
- const webpackConfigs = [isSSR(userConfig) && getWebpackConfig(WebpackConfigTarget.NODE, appContext, userConfig), getWebpackConfig(WebpackConfigTarget.CLIENT, appContext, userConfig)].filter(Boolean);
56
- compiler = await createCompiler({
57
- api,
58
- webpackConfigs,
59
- userConfig,
60
- appContext
61
- });
46
+ var _appContext$builder;
47
+ compiler = await ((_appContext$builder = appContext.builder) === null || _appContext$builder === void 0 ? void 0 : _appContext$builder.createCompiler());
62
48
  }
63
-
64
49
  await generateRoutes(appContext);
65
50
  const app = await createServer({
66
51
  dev: _objectSpread(_objectSpread({}, {
@@ -79,17 +64,16 @@ export const dev = async (api, options) => {
79
64
  pwd: appDirectory,
80
65
  config: userConfig,
81
66
  serverConfigFile,
82
- plugins: appContext.plugins.filter(p => p.server).map(p => p.server)
67
+ internalPlugins: injectDataLoaderPlugin(serverInternalPlugins)
83
68
  });
84
69
  app.listen(port, async err => {
85
70
  if (err) {
86
71
  throw err;
87
72
  }
88
-
89
- if (apiOnly) {
90
- return printInstructions(hookRunners, appContext, userConfig);
73
+ if (!apiOnly) {
74
+ logger.info(`Starting dev server...\n`);
75
+ } else {
76
+ printInstructions(hookRunners, appContext, userConfig);
91
77
  }
92
-
93
- return logger.log(chalk.cyan(`Starting the development server...`));
94
78
  });
95
79
  };
@@ -1,69 +1,11 @@
1
- import path from 'path';
2
- import { getWebpackConfig, WebpackConfigTarget } from '@modern-js/webpack';
3
- import { fs, logger, isUseSSRBundle, chalk } from '@modern-js/utils';
4
- import WebpackChain from '@modern-js/utils/webpack-chain';
5
- export const formatWebpackConfig = (config, verbose) => {
6
- const stringify = WebpackChain.toString;
7
- return `module.exports = ${stringify(config, {
8
- verbose
9
- })};`;
10
- };
11
- export const inspect = (api, options) => {
12
- process.env.NODE_ENV = options.env;
13
- const resolvedConfig = api.useResolvedConfigContext();
1
+ import { join } from 'path';
2
+ export const inspect = async (api, options) => {
3
+ var _appContext$builder;
14
4
  const appContext = api.useAppContext();
15
- const outputFiles = [];
16
- outputFiles.push(printInspectResult(WebpackConfigTarget.CLIENT, appContext, resolvedConfig, options));
17
-
18
- if (resolvedConfig.output.enableModernMode) {
19
- outputFiles.push(printInspectResult(WebpackConfigTarget.MODERN, appContext, resolvedConfig, options));
20
- }
21
-
22
- if (isUseSSRBundle(resolvedConfig)) {
23
- outputFiles.push(printInspectResult(WebpackConfigTarget.NODE, appContext, resolvedConfig, options));
24
- }
25
-
26
- logger.success('Inspect succeed, you can open following files to view the full webpack config: \n');
27
- outputFiles.forEach(file => {
28
- logger.log(` - ${chalk.yellow(path.relative(appContext.appDirectory, file))}`);
5
+ return (_appContext$builder = appContext.builder) === null || _appContext$builder === void 0 ? void 0 : _appContext$builder.inspectConfig({
6
+ env: options.env,
7
+ verbose: options.verbose,
8
+ outputPath: join(appContext === null || appContext === void 0 ? void 0 : appContext.builder.context.distPath, options.output),
9
+ writeToDisk: true
29
10
  });
30
- logger.log();
31
- };
32
- export const getTagByWebpackTarget = webpackTarget => {
33
- switch (webpackTarget) {
34
- case WebpackConfigTarget.CLIENT:
35
- return 'client';
36
-
37
- case WebpackConfigTarget.MODERN:
38
- return 'modern';
39
-
40
- case WebpackConfigTarget.NODE:
41
- return 'ssr';
42
-
43
- default:
44
- throw Error(`Unsupported webpack target: ${webpackTarget}`);
45
- }
46
- };
47
- export const printInspectResult = (webpackTarget, appContext, resolvedConfig, options) => {
48
- const webpackConfig = getWebpackConfig(webpackTarget, appContext, resolvedConfig);
49
- const {
50
- output,
51
- verbose,
52
- console = true
53
- } = options;
54
- const outputPath = output ? path.posix.join(appContext.distDirectory, output) : appContext.distDirectory;
55
- const tag = getTagByWebpackTarget(webpackTarget);
56
- const outputFile = `webpack.${tag}.inspect.js`;
57
- const outputFilePath = path.posix.join(outputPath, outputFile);
58
- const rawWebpackConfig = formatWebpackConfig(webpackConfig, verbose);
59
- fs.outputFileSync(outputFilePath, rawWebpackConfig);
60
-
61
- if (console) {
62
- logger.log(`
63
- webpack config for ${tag} build:
64
- ${rawWebpackConfig}
65
- `);
66
- }
67
-
68
- return outputFilePath;
69
11
  };
@@ -1,9 +1,9 @@
1
1
  import { logger, chalk, isApiOnly } from '@modern-js/utils';
2
2
  import server from '@modern-js/prod-server';
3
3
  import { printInstructions } from "../utils/printInstructions";
4
+ import { injectDataLoaderPlugin } from "../utils/createServer";
4
5
  export const start = async api => {
5
6
  var _userConfig$source;
6
-
7
7
  const appContext = api.useAppContext();
8
8
  const userConfig = api.useResolvedConfigContext();
9
9
  const hookRunners = api.useHookRunners();
@@ -17,15 +17,14 @@ export const start = async api => {
17
17
  const app = await server({
18
18
  pwd: appDirectory,
19
19
  config: userConfig,
20
- plugins: appContext.plugins.filter(p => p.server).map(p => p.server),
21
20
  serverConfigFile,
21
+ internalPlugins: injectDataLoaderPlugin(appContext.serverInternalPlugins),
22
22
  apiOnly
23
23
  });
24
24
  app.listen(port, async err => {
25
25
  if (err) {
26
26
  throw err;
27
27
  }
28
-
29
28
  await printInstructions(hookRunners, appContext, userConfig);
30
29
  });
31
30
  };
@@ -1,22 +1,20 @@
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
-
3
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; }
4
-
5
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; }
6
-
7
4
  import path from 'path';
8
5
  import { defineConfig, cli } from '@modern-js/core';
9
- import LintPlugin from '@modern-js/plugin-jarvis';
10
- import { cleanRequireCache, Import } from '@modern-js/utils';
6
+ import LintPlugin from '@modern-js/plugin-lint';
7
+ import { cleanRequireCache, emptyDir, Import } from '@modern-js/utils';
11
8
  import AnalyzePlugin from "./analyze";
12
9
  import { hooks } from "./hooks";
13
10
  import { i18n, localeKeys } from "./locale";
14
11
  import { getLocaleLanguage } from "./utils/language";
15
- export { defineConfig };
12
+ import { getCommand } from "./utils/commands";
13
+ export { defineConfig, hooks };
16
14
  const upgradeModel = Import.lazy('@modern-js/upgrade', require);
17
15
  export default (() => ({
18
16
  name: '@modern-js/app-tools',
19
- post: ['@modern-js/plugin-analyze', '@modern-js/plugin-ssr', '@modern-js/plugin-state', '@modern-js/plugin-router', '@modern-js/plugin-polyfill'],
17
+ post: ['@modern-js/plugin-analyze', '@modern-js/plugin-ssr', '@modern-js/plugin-document', '@modern-js/plugin-state', '@modern-js/plugin-router', '@modern-js/plugin-router-legacy', '@modern-js/plugin-polyfill'],
20
18
  registerHook: hooks,
21
19
  usePlugins: [AnalyzePlugin(), LintPlugin()],
22
20
  setup: api => {
@@ -38,9 +36,9 @@ export default (() => ({
38
36
  const {
39
37
  build
40
38
  } = await import("./commands/build");
41
- await build(api, options); // force exit after build.
39
+ await build(api, options);
40
+ // force exit after build.
42
41
  // eslint-disable-next-line no-process-exit
43
-
44
42
  process.exit(0);
45
43
  });
46
44
  program.command('start').usage('[options]').description(i18n.t(localeKeys.command.start.describe)).option('--api-only', i18n.t(localeKeys.command.dev.apiOnly)).option('-c --config <config>', i18n.t(localeKeys.command.shared.config)).action(async () => {
@@ -57,8 +55,8 @@ export default (() => ({
57
55
  const {
58
56
  deploy
59
57
  } = await import("./commands/deploy");
60
- await deploy(api, options); // eslint-disable-next-line no-process-exit
61
-
58
+ await deploy(api, options);
59
+ // eslint-disable-next-line no-process-exit
62
60
  process.exit(0);
63
61
  });
64
62
  program.command('new').usage('[options]').description(i18n.t(localeKeys.command.new.describe)).option('-d, --debug', i18n.t(localeKeys.command.new.debug), false).option('-c, --config <config>', i18n.t(localeKeys.command.new.config)).option('--dist-tag <tag>', i18n.t(localeKeys.command.new.distTag)).option('--registry', i18n.t(localeKeys.command.new.registry)).action(async options => {
@@ -69,7 +67,7 @@ export default (() => ({
69
67
  locale
70
68
  }));
71
69
  });
72
- program.command('inspect').description('inspect internal webpack config').option(`--env <env>`, i18n.t(localeKeys.command.inspect.env), 'development').option('--output <output>', i18n.t(localeKeys.command.inspect.output), '/').option('--no-console', i18n.t(localeKeys.command.inspect.noConsole)).option('--verbose', i18n.t(localeKeys.command.inspect.verbose)).option('-c --config <config>', i18n.t(localeKeys.command.shared.config)).action(async options => {
70
+ program.command('inspect').description('inspect internal webpack config').option(`--env <env>`, i18n.t(localeKeys.command.inspect.env), 'development').option('--output <output>', i18n.t(localeKeys.command.inspect.output), '/').option('--verbose', i18n.t(localeKeys.command.inspect.verbose)).option('-c --config <config>', i18n.t(localeKeys.command.shared.config)).action(async options => {
73
71
  const {
74
72
  inspect
75
73
  } = await import("./commands/inspect");
@@ -77,7 +75,13 @@ export default (() => ({
77
75
  });
78
76
  upgradeModel.defineCommand(program.command('upgrade'));
79
77
  },
80
-
78
+ async prepare() {
79
+ const command = getCommand();
80
+ if (command === 'dev' || command === 'build') {
81
+ const appContext = api.useAppContext();
82
+ await emptyDir(appContext.distDirectory);
83
+ }
84
+ },
81
85
  // 这里会被 core/initWatcher 监听的文件变动触发,如果是 src 目录下的文件变动,则不做 restart
82
86
  async fileChange(e) {
83
87
  const {
@@ -90,7 +94,6 @@ export default (() => ({
90
94
  srcDirectory
91
95
  } = appContext;
92
96
  const absolutePath = path.resolve(appDirectory, filename);
93
-
94
97
  if (!absolutePath.includes(srcDirectory) && (eventType === 'change' || eventType === 'unlink')) {
95
98
  const {
96
99
  closeServer
@@ -99,11 +102,9 @@ export default (() => ({
99
102
  await cli.restart();
100
103
  }
101
104
  },
102
-
103
105
  async beforeRestart() {
104
106
  cleanRequireCache([require.resolve("./analyze")]);
105
107
  }
106
-
107
108
  };
108
109
  }
109
110
  }));
@@ -28,7 +28,6 @@ export const EN_LOCALE = {
28
28
  inspect: {
29
29
  env: 'specify env mode',
30
30
  output: 'specify inspect content output path',
31
- noConsole: 'do not log the result in terminal',
32
31
  verbose: 'show full function definitions in output'
33
32
  }
34
33
  }
@@ -28,7 +28,6 @@ export const ZH_LOCALE = {
28
28
  inspect: {
29
29
  env: '查看指定环境下的配置',
30
30
  output: '指定在 dist 目录下输出的路径',
31
- noConsole: '不在终端中输出完整结果',
32
31
  verbose: '在结果中展示函数的完整内容'
33
32
  }
34
33
  }