@modern-js/app-tools 2.52.0 → 2.53.1-alpha.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (79) hide show
  1. package/dist/cjs/plugins/deploy/dependencies/index.js +1 -11
  2. package/dist/cjs/plugins/deploy/platforms/netlify.js +1 -1
  3. package/dist/cjs/plugins/deploy/platforms/node.js +1 -1
  4. package/dist/cjs/plugins/deploy/platforms/vercel.js +1 -1
  5. package/dist/esm/plugins/deploy/dependencies/index.js +4 -14
  6. package/dist/esm/plugins/deploy/platforms/netlify.js +1 -1
  7. package/dist/esm/plugins/deploy/platforms/node.js +1 -1
  8. package/dist/esm/plugins/deploy/platforms/vercel.js +1 -1
  9. package/dist/esm-node/plugins/deploy/dependencies/index.js +2 -12
  10. package/dist/esm-node/plugins/deploy/platforms/netlify.js +1 -1
  11. package/dist/esm-node/plugins/deploy/platforms/node.js +1 -1
  12. package/dist/esm-node/plugins/deploy/platforms/vercel.js +1 -1
  13. package/dist/js/modern/analyze/constants.js +15 -0
  14. package/dist/js/modern/analyze/generateCode.js +179 -0
  15. package/dist/js/modern/analyze/getBundleEntry.js +75 -0
  16. package/dist/js/modern/analyze/getClientRoutes.js +219 -0
  17. package/dist/js/modern/analyze/getFileSystemEntry.js +74 -0
  18. package/dist/js/modern/analyze/getHtmlTemplate.js +82 -0
  19. package/dist/js/modern/analyze/getServerRoutes.js +192 -0
  20. package/dist/js/modern/analyze/index.js +148 -0
  21. package/dist/js/modern/analyze/isDefaultExportFunction.js +32 -0
  22. package/dist/js/modern/analyze/makeLegalIdentifier.js +16 -0
  23. package/dist/js/modern/analyze/templates.js +88 -0
  24. package/dist/js/modern/analyze/utils.js +92 -0
  25. package/dist/js/modern/commands/build.js +154 -0
  26. package/dist/js/modern/commands/deploy.js +5 -0
  27. package/dist/js/modern/commands/dev.js +95 -0
  28. package/dist/js/modern/commands/index.js +3 -0
  29. package/dist/js/modern/commands/inspect.js +69 -0
  30. package/dist/js/modern/commands/start.js +31 -0
  31. package/dist/js/modern/exports/server.js +1 -0
  32. package/dist/js/modern/hooks.js +21 -0
  33. package/dist/js/modern/index.js +109 -0
  34. package/dist/js/modern/locale/en.js +35 -0
  35. package/dist/js/modern/locale/index.js +9 -0
  36. package/dist/js/modern/locale/zh.js +35 -0
  37. package/dist/js/modern/utils/config.js +78 -0
  38. package/dist/js/modern/utils/createCompiler.js +61 -0
  39. package/dist/js/modern/utils/createServer.js +18 -0
  40. package/dist/js/modern/utils/getSpecifiedEntries.js +36 -0
  41. package/dist/js/modern/utils/language.js +5 -0
  42. package/dist/js/modern/utils/printInstructions.js +11 -0
  43. package/dist/js/modern/utils/routes.js +15 -0
  44. package/dist/js/modern/utils/types.js +0 -0
  45. package/dist/js/node/analyze/constants.js +36 -0
  46. package/dist/js/node/analyze/generateCode.js +208 -0
  47. package/dist/js/node/analyze/getBundleEntry.js +89 -0
  48. package/dist/js/node/analyze/getClientRoutes.js +241 -0
  49. package/dist/js/node/analyze/getFileSystemEntry.js +90 -0
  50. package/dist/js/node/analyze/getHtmlTemplate.js +106 -0
  51. package/dist/js/node/analyze/getServerRoutes.js +208 -0
  52. package/dist/js/node/analyze/index.js +178 -0
  53. package/dist/js/node/analyze/isDefaultExportFunction.js +50 -0
  54. package/dist/js/node/analyze/makeLegalIdentifier.js +24 -0
  55. package/dist/js/node/analyze/templates.js +106 -0
  56. package/dist/js/node/analyze/utils.js +113 -0
  57. package/dist/js/node/commands/build.js +174 -0
  58. package/dist/js/node/commands/deploy.js +14 -0
  59. package/dist/js/node/commands/dev.js +120 -0
  60. package/dist/js/node/commands/index.js +44 -0
  61. package/dist/js/node/commands/inspect.js +98 -0
  62. package/dist/js/node/commands/start.js +47 -0
  63. package/dist/js/node/exports/server.js +13 -0
  64. package/dist/js/node/hooks.js +39 -0
  65. package/dist/js/node/index.js +141 -0
  66. package/dist/js/node/locale/en.js +42 -0
  67. package/dist/js/node/locale/index.js +20 -0
  68. package/dist/js/node/locale/zh.js +42 -0
  69. package/dist/js/node/utils/config.js +103 -0
  70. package/dist/js/node/utils/createCompiler.js +81 -0
  71. package/dist/js/node/utils/createServer.js +35 -0
  72. package/dist/js/node/utils/getSpecifiedEntries.js +46 -0
  73. package/dist/js/node/utils/language.js +13 -0
  74. package/dist/js/node/utils/printInstructions.js +22 -0
  75. package/dist/js/node/utils/routes.js +25 -0
  76. package/dist/js/node/utils/types.js +0 -0
  77. package/dist/types/config/initialize/inits.d.ts +1 -1
  78. package/dist/types/plugins/deploy/dependencies/index.d.ts +1 -1
  79. package/package.json +17 -17
@@ -0,0 +1,92 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { isReact18, normalizeToPosixPath } from '@modern-js/utils';
4
+ import { FILE_SYSTEM_ROUTES_FILE_NAME } from "./constants";
5
+ export const walkDirectory = dir => fs.readdirSync(dir).reduce((previous, filename) => {
6
+ const filePath = path.join(dir, filename);
7
+
8
+ if (fs.statSync(filePath).isDirectory()) {
9
+ return [...previous, ...walkDirectory(filePath)];
10
+ } else {
11
+ return [...previous, filePath];
12
+ }
13
+ }, []);
14
+ export const getDefaultImports = ({
15
+ entrypoint,
16
+ srcDirectory,
17
+ internalSrcAlias,
18
+ internalDirAlias,
19
+ internalDirectory
20
+ }) => {
21
+ const {
22
+ entryName,
23
+ fileSystemRoutes,
24
+ customBootstrap,
25
+ entry
26
+ } = entrypoint;
27
+ const imports = [{
28
+ specifiers: [{
29
+ local: 'React'
30
+ }],
31
+ value: 'react'
32
+ }, {
33
+ specifiers: [{
34
+ local: 'ReactDOM'
35
+ }],
36
+ value: isReact18(path.join(internalDirectory, '../../')) ? 'react-dom/client' : 'react-dom'
37
+ }, {
38
+ specifiers: [{
39
+ imported: 'createApp'
40
+ }, {
41
+ imported: 'bootstrap'
42
+ }],
43
+ value: '@modern-js/runtime'
44
+ }, customBootstrap && {
45
+ specifiers: [{
46
+ local: 'customBootstrap'
47
+ }],
48
+ value: normalizeToPosixPath(customBootstrap.replace(srcDirectory, internalSrcAlias))
49
+ }].filter(Boolean);
50
+
51
+ if (fileSystemRoutes) {
52
+ const route = {
53
+ specifiers: [{
54
+ imported: 'routes'
55
+ }],
56
+ value: normalizeToPosixPath(`${internalDirAlias}/${entryName}/${FILE_SYSTEM_ROUTES_FILE_NAME}`)
57
+ };
58
+
59
+ if (fileSystemRoutes.globalApp) {
60
+ imports.push({
61
+ specifiers: [{
62
+ local: 'App'
63
+ }],
64
+ value: normalizeToPosixPath(fileSystemRoutes.globalApp.replace(srcDirectory, internalSrcAlias))
65
+ });
66
+ } else {
67
+ route.initialize = 'const App = false;';
68
+ }
69
+
70
+ imports.push(route);
71
+ } else {
72
+ imports.push({
73
+ specifiers: [{
74
+ local: 'App'
75
+ }],
76
+ value: normalizeToPosixPath(entry.replace(srcDirectory, internalSrcAlias))
77
+ });
78
+ }
79
+
80
+ return imports;
81
+ };
82
+ export const isRouteComponentFile = filePath => {
83
+ if (/\.(d|test|spec|e2e)\.(js|jsx|ts|tsx)$/.test(filePath)) {
84
+ return false;
85
+ }
86
+
87
+ if (['.js', '.jsx', '.ts', '.tsx'].includes(path.extname(filePath))) {
88
+ return true;
89
+ }
90
+
91
+ return false;
92
+ };
@@ -0,0 +1,154 @@
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
+ 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
+ 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
+ import { ResolvedConfigContext } from '@modern-js/core';
9
+ import { formatWebpackMessages, measureFileSizesBeforeBuild, printFileSizesAfterBuild, printBuildError, logger, isUseSSRBundle, emptyDir } from '@modern-js/utils';
10
+ 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;
15
+ export const build = async (api, options) => {
16
+ let resolvedConfig = api.useResolvedConfigContext();
17
+ const appContext = api.useAppContext();
18
+ const hookRunners = api.useHookRunners();
19
+ const {
20
+ apiOnly
21
+ } = appContext;
22
+
23
+ if (apiOnly) {
24
+ const {
25
+ appDirectory,
26
+ distDirectory,
27
+ serverConfigFile
28
+ } = appContext;
29
+ await emptyDir(distDirectory);
30
+ await hookRunners.beforeBuild({
31
+ webpackConfigs: []
32
+ });
33
+ await buildServerConfig({
34
+ appDirectory,
35
+ distDirectory,
36
+ configFile: serverConfigFile
37
+ });
38
+ await generateRoutes(appContext);
39
+ await hookRunners.afterBuild();
40
+ return;
41
+ }
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
+ resolvedConfig = _objectSpread(_objectSpread({}, resolvedConfig), {}, {
95
+ cliOptions: options
96
+ });
97
+ ResolvedConfigContext.set(resolvedConfig);
98
+ const {
99
+ distDirectory,
100
+ appDirectory,
101
+ serverConfigFile
102
+ } = appContext;
103
+ const previousFileSizes = await measureFileSizesBeforeBuild(distDirectory);
104
+ await emptyDir(distDirectory);
105
+ await buildServerConfig({
106
+ appDirectory,
107
+ distDirectory,
108
+ configFile: serverConfigFile
109
+ });
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
+ }
149
+ }
150
+
151
+ await generateRoutes(appContext);
152
+ await hookRunners.afterBuild();
153
+ await emitResolvedConfig(appDirectory, resolvedConfig);
154
+ };
@@ -0,0 +1,5 @@
1
+ export const deploy = async (api, options) => {
2
+ const hookRunners = api.useHookRunners();
3
+ await hookRunners.beforeDeploy(options);
4
+ await hookRunners.afterDeploy(options);
5
+ };
@@ -0,0 +1,95 @@
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
+ 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
+ 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';
8
+ 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
+ import { printInstructions } from "../utils/printInstructions";
13
+ import { getSpecifiedEntries } from "../utils/getSpecifiedEntries";
14
+ import { buildServerConfig } from "../utils/config";
15
+ export const dev = async (api, options) => {
16
+ let userConfig = api.useResolvedConfigContext();
17
+ const appContext = api.useAppContext();
18
+ const hookRunners = api.useHookRunners();
19
+ userConfig = _objectSpread(_objectSpread({}, userConfig), {}, {
20
+ cliOptions: options
21
+ });
22
+ ResolvedConfigContext.set(userConfig);
23
+ const {
24
+ appDirectory,
25
+ distDirectory,
26
+ port,
27
+ apiOnly,
28
+ entrypoints,
29
+ serverConfigFile
30
+ } = appContext;
31
+ const checkedEntries = await getSpecifiedEntries(options.entry || false, entrypoints);
32
+ api.setAppContext(_objectSpread(_objectSpread({}, appContext), {}, {
33
+ checkedEntries
34
+ }));
35
+ appContext.checkedEntries = checkedEntries;
36
+ fs.emptyDirSync(distDirectory);
37
+ await buildServerConfig({
38
+ appDirectory,
39
+ distDirectory,
40
+ configFile: serverConfigFile,
41
+ options: {
42
+ esbuildOptions: {
43
+ watch: true
44
+ }
45
+ }
46
+ });
47
+ await hookRunners.beforeDev();
48
+ let compiler = null;
49
+
50
+ 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
+ });
62
+ }
63
+
64
+ await generateRoutes(appContext);
65
+ const app = await createServer({
66
+ dev: _objectSpread(_objectSpread({}, {
67
+ client: {
68
+ port: port.toString()
69
+ },
70
+ devMiddleware: {
71
+ writeToDisk: file => !file.includes('.hot-update.')
72
+ },
73
+ hot: true,
74
+ liveReload: true,
75
+ port,
76
+ https: userConfig.dev.https
77
+ }), userConfig.tools.devServer),
78
+ compiler,
79
+ pwd: appDirectory,
80
+ config: userConfig,
81
+ serverConfigFile,
82
+ plugins: appContext.plugins.filter(p => p.server).map(p => p.server)
83
+ });
84
+ app.listen(port, async err => {
85
+ if (err) {
86
+ throw err;
87
+ }
88
+
89
+ if (apiOnly) {
90
+ return printInstructions(hookRunners, appContext, userConfig);
91
+ }
92
+
93
+ return logger.log(chalk.cyan(`Starting the development server...`));
94
+ });
95
+ };
@@ -0,0 +1,3 @@
1
+ export * from "./dev";
2
+ export * from "./build";
3
+ export * from "./start";
@@ -0,0 +1,69 @@
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();
14
+ 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))}`);
29
+ });
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
+ };
@@ -0,0 +1,31 @@
1
+ import { logger, chalk, isApiOnly } from '@modern-js/utils';
2
+ import server from '@modern-js/prod-server';
3
+ import { printInstructions } from "../utils/printInstructions";
4
+ export const start = async api => {
5
+ var _userConfig$source;
6
+
7
+ const appContext = api.useAppContext();
8
+ const userConfig = api.useResolvedConfigContext();
9
+ const hookRunners = api.useHookRunners();
10
+ const {
11
+ appDirectory,
12
+ port,
13
+ serverConfigFile
14
+ } = appContext;
15
+ logger.log(chalk.cyan(`Starting the modern server...`));
16
+ const apiOnly = await isApiOnly(appContext.appDirectory, userConfig === null || userConfig === void 0 ? void 0 : (_userConfig$source = userConfig.source) === null || _userConfig$source === void 0 ? void 0 : _userConfig$source.entriesDir);
17
+ const app = await server({
18
+ pwd: appDirectory,
19
+ config: userConfig,
20
+ plugins: appContext.plugins.filter(p => p.server).map(p => p.server),
21
+ serverConfigFile,
22
+ apiOnly
23
+ });
24
+ app.listen(port, async err => {
25
+ if (err) {
26
+ throw err;
27
+ }
28
+
29
+ await printInstructions(hookRunners, appContext, userConfig);
30
+ });
31
+ };
@@ -0,0 +1 @@
1
+ export { defineServerConfig as defineConfig } from "../utils/config";
@@ -0,0 +1,21 @@
1
+ import { createAsyncWaterfall, createAsyncWorkflow } from '@modern-js/plugin';
2
+ export const beforeDev = createAsyncWorkflow();
3
+ export const afterDev = createAsyncWorkflow();
4
+ export const beforeCreateCompiler = createAsyncWorkflow();
5
+ export const afterCreateCompiler = createAsyncWorkflow();
6
+ export const beforePrintInstructions = createAsyncWaterfall();
7
+ export const beforeBuild = createAsyncWorkflow();
8
+ export const afterBuild = createAsyncWorkflow();
9
+ export const beforeDeploy = createAsyncWorkflow();
10
+ export const afterDeploy = createAsyncWorkflow();
11
+ export const hooks = {
12
+ beforeDev,
13
+ afterDev,
14
+ beforeCreateCompiler,
15
+ afterCreateCompiler,
16
+ beforePrintInstructions,
17
+ beforeBuild,
18
+ afterBuild,
19
+ beforeDeploy,
20
+ afterDeploy
21
+ };
@@ -0,0 +1,109 @@
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
+ 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
+ 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 path from 'path';
8
+ import { defineConfig, cli } from '@modern-js/core';
9
+ import LintPlugin from '@modern-js/plugin-jarvis';
10
+ import { cleanRequireCache, Import } from '@modern-js/utils';
11
+ import AnalyzePlugin from "./analyze";
12
+ import { hooks } from "./hooks";
13
+ import { i18n, localeKeys } from "./locale";
14
+ import { getLocaleLanguage } from "./utils/language";
15
+ export { defineConfig };
16
+ const upgradeModel = Import.lazy('@modern-js/upgrade', require);
17
+ export default (() => ({
18
+ 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'],
20
+ registerHook: hooks,
21
+ usePlugins: [AnalyzePlugin(), LintPlugin()],
22
+ setup: api => {
23
+ const locale = getLocaleLanguage();
24
+ i18n.changeLanguage({
25
+ locale
26
+ });
27
+ return {
28
+ commands({
29
+ program
30
+ }) {
31
+ program.command('dev').usage('[options]').description(i18n.t(localeKeys.command.dev.describe)).option('-c --config <config>', i18n.t(localeKeys.command.shared.config)).option('-e --entry [entry...]', i18n.t(localeKeys.command.dev.entry)).option('--analyze', i18n.t(localeKeys.command.shared.analyze)).option('--api-only', i18n.t(localeKeys.command.dev.apiOnly)).action(async options => {
32
+ const {
33
+ dev
34
+ } = await import("./commands/dev");
35
+ await dev(api, options);
36
+ });
37
+ program.command('build').usage('[options]').description(i18n.t(localeKeys.command.build.describe)).option('-c --config <config>', i18n.t(localeKeys.command.shared.config)).option('--analyze', i18n.t(localeKeys.command.shared.analyze)).action(async options => {
38
+ const {
39
+ build
40
+ } = await import("./commands/build");
41
+ await build(api, options); // force exit after build.
42
+ // eslint-disable-next-line no-process-exit
43
+
44
+ process.exit(0);
45
+ });
46
+ 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 () => {
47
+ const {
48
+ start
49
+ } = await import("./commands/start");
50
+ await start(api);
51
+ });
52
+ program.command('deploy').usage('[options]').option('-c --config <config>', i18n.t(localeKeys.command.shared.config)).description(i18n.t(localeKeys.command.deploy.describe)).action(async options => {
53
+ const {
54
+ build
55
+ } = await import("./commands/build");
56
+ await build(api);
57
+ const {
58
+ deploy
59
+ } = await import("./commands/deploy");
60
+ await deploy(api, options); // eslint-disable-next-line no-process-exit
61
+
62
+ process.exit(0);
63
+ });
64
+ 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 => {
65
+ const {
66
+ MWANewAction
67
+ } = await import('@modern-js/new-action');
68
+ await MWANewAction(_objectSpread(_objectSpread({}, options), {}, {
69
+ locale
70
+ }));
71
+ });
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 => {
73
+ const {
74
+ inspect
75
+ } = await import("./commands/inspect");
76
+ inspect(api, options);
77
+ });
78
+ upgradeModel.defineCommand(program.command('upgrade'));
79
+ },
80
+
81
+ // 这里会被 core/initWatcher 监听的文件变动触发,如果是 src 目录下的文件变动,则不做 restart
82
+ async fileChange(e) {
83
+ const {
84
+ filename,
85
+ eventType
86
+ } = e;
87
+ const appContext = api.useAppContext();
88
+ const {
89
+ appDirectory,
90
+ srcDirectory
91
+ } = appContext;
92
+ const absolutePath = path.resolve(appDirectory, filename);
93
+
94
+ if (!absolutePath.includes(srcDirectory) && (eventType === 'change' || eventType === 'unlink')) {
95
+ const {
96
+ closeServer
97
+ } = await import("./utils/createServer");
98
+ await closeServer();
99
+ await cli.restart();
100
+ }
101
+ },
102
+
103
+ async beforeRestart() {
104
+ cleanRequireCache([require.resolve("./analyze")]);
105
+ }
106
+
107
+ };
108
+ }
109
+ }));
@@ -0,0 +1,35 @@
1
+ export const EN_LOCALE = {
2
+ command: {
3
+ shared: {
4
+ analyze: 'analyze bundle size',
5
+ config: 'specify config file'
6
+ },
7
+ dev: {
8
+ describe: 'start dev server',
9
+ entry: 'compiler by entry',
10
+ apiOnly: 'start api server only'
11
+ },
12
+ build: {
13
+ describe: 'build application'
14
+ },
15
+ start: {
16
+ describe: 'start server'
17
+ },
18
+ deploy: {
19
+ describe: 'deploy application'
20
+ },
21
+ new: {
22
+ describe: 'generator runner for MWA project',
23
+ debug: 'using debug mode to log something',
24
+ config: 'set default generator config(json string)',
25
+ distTag: `use specified tag version for it's generator`,
26
+ registry: 'set npm registry url to run npm command'
27
+ },
28
+ inspect: {
29
+ env: 'specify env mode',
30
+ output: 'specify inspect content output path',
31
+ noConsole: 'do not log the result in terminal',
32
+ verbose: 'show full function definitions in output'
33
+ }
34
+ }
35
+ };
@@ -0,0 +1,9 @@
1
+ import { I18n } from '@modern-js/plugin-i18n';
2
+ import { ZH_LOCALE } from "./zh";
3
+ import { EN_LOCALE } from "./en";
4
+ const i18n = new I18n();
5
+ const localeKeys = i18n.init('zh', {
6
+ zh: ZH_LOCALE,
7
+ en: EN_LOCALE
8
+ });
9
+ export { i18n, localeKeys };
@@ -0,0 +1,35 @@
1
+ export const ZH_LOCALE = {
2
+ command: {
3
+ shared: {
4
+ analyze: '分析构建产物体积,查看各个模块打包后的大小',
5
+ config: '指定配置文件路径,可以为相对路径或绝对路径'
6
+ },
7
+ dev: {
8
+ describe: '本地开发命令',
9
+ entry: '指定入口,编译特定的页面',
10
+ apiOnly: '仅启动 API 接口服务'
11
+ },
12
+ build: {
13
+ describe: '构建应用命令'
14
+ },
15
+ start: {
16
+ describe: '应用启动命令'
17
+ },
18
+ deploy: {
19
+ describe: '部署应用命令'
20
+ },
21
+ new: {
22
+ describe: 'MWA 项目中执行生成器',
23
+ debug: '开启 Debug 模式,打印调试日志信息',
24
+ config: '生成器运行默认配置(JSON 字符串)',
25
+ distTag: '生成器使用特殊的 npm Tag 版本',
26
+ registry: '生成器运行过程中定制 npm Registry'
27
+ },
28
+ inspect: {
29
+ env: '查看指定环境下的配置',
30
+ output: '指定在 dist 目录下输出的路径',
31
+ noConsole: '不在终端中输出完整结果',
32
+ verbose: '在结果中展示函数的完整内容'
33
+ }
34
+ }
35
+ };