@modern-js/plugin-ssg 1.2.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # @modern-js/plugin-ssg
2
2
 
3
+ ## 1.2.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 83166714: change .npmignore
8
+ - Updated dependencies [83166714]
9
+ - Updated dependencies [c3de9882]
10
+ - Updated dependencies [33ff48af]
11
+ - @modern-js/core@1.3.2
12
+ - @modern-js/utils@1.2.2
13
+
3
14
  ## 1.2.0
4
15
 
5
16
  ### Minor Changes
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "modern",
12
12
  "modern.js"
13
13
  ],
14
- "version": "1.2.0",
14
+ "version": "1.2.1",
15
15
  "jsnext:source": "./src/index.ts",
16
16
  "types": "./dist/types/index.d.ts",
17
17
  "main": "./dist/js/node/index.js",
@@ -37,15 +37,15 @@
37
37
  },
38
38
  "dependencies": {
39
39
  "@babel/runtime": "^7",
40
- "@modern-js/utils": "^1.2.0",
40
+ "@modern-js/utils": "^1.2.2",
41
41
  "node-mocks-http": "^1.10.1",
42
42
  "normalize-path": "^3.0.0",
43
43
  "portfinder": "^1.0.28",
44
44
  "react-router-dom": "^5.2.1"
45
45
  },
46
46
  "devDependencies": {
47
- "@modern-js/server": "^1.3.0",
48
- "@modern-js/types": "^1.2.0",
47
+ "@modern-js/server": "^1.3.2",
48
+ "@modern-js/types": "^1.2.1",
49
49
  "@types/jest": "^26",
50
50
  "@types/node": "^14",
51
51
  "@types/react": "^17",
@@ -53,13 +53,13 @@
53
53
  "@types/react-router": "^5.1.16",
54
54
  "@types/react-router-dom": "^5.1.8",
55
55
  "typescript": "^4",
56
- "@modern-js/core": "^1.3.0",
56
+ "@modern-js/core": "^1.3.2",
57
57
  "@scripts/build": "0.0.0",
58
58
  "jest": "^27",
59
59
  "@scripts/jest-config": "0.0.0"
60
60
  },
61
61
  "peerDependencies": {
62
- "@modern-js/core": "^1.3.0"
62
+ "@modern-js/core": "^1.3.2"
63
63
  },
64
64
  "sideEffects": false,
65
65
  "modernConfig": {
package/src/global.d.ts DELETED
@@ -1 +0,0 @@
1
- declare module 'normalize-path';
package/src/index.ts DELETED
@@ -1,209 +0,0 @@
1
- import path from 'path';
2
- import { logger, PLUGIN_SCHEMAS } from '@modern-js/utils';
3
- import {
4
- createPlugin,
5
- useAppContext,
6
- useResolvedConfigContext,
7
- } from '@modern-js/core';
8
- import { generatePath } from 'react-router-dom';
9
- import {
10
- AgreedRoute,
11
- AgreedRouteMap,
12
- EntryPoint,
13
- ExtendOutputConfig,
14
- SSG,
15
- SsgRoute,
16
- } from './types';
17
- import {
18
- formatOutput,
19
- isDynamicUrl,
20
- readJSONSpec,
21
- standardOptions,
22
- writeJSONSpec,
23
- } from './libs/util';
24
- import { createServer } from './server';
25
- import { writeHtmlFile } from './libs/output';
26
- import { replaceRoute } from './libs/replace';
27
- import { makeRoute } from './libs/make';
28
-
29
- export default createPlugin(
30
- (() => {
31
- const agreedRouteMap: AgreedRouteMap = {};
32
-
33
- return {
34
- validateSchema() {
35
- return PLUGIN_SCHEMAS['@modern-js/plugin-ssg'];
36
- },
37
- modifyFileSystemRoutes({
38
- entrypoint,
39
- routes,
40
- }: {
41
- entrypoint: EntryPoint;
42
- routes: AgreedRoute[];
43
- }) {
44
- const { entryName } = entrypoint;
45
- agreedRouteMap[entryName] = routes;
46
-
47
- return { entrypoint, routes };
48
- },
49
- // eslint-disable-next-line max-statements
50
- async afterBuild() {
51
- // eslint-disable-next-line react-hooks/rules-of-hooks
52
- const resolvedConfig = useResolvedConfigContext();
53
- // eslint-disable-next-line react-hooks/rules-of-hooks
54
- const appContext = useAppContext();
55
-
56
- const { appDirectory, entrypoints } = appContext;
57
- const { output } = resolvedConfig;
58
- const { ssg, path: outputPath } = output as typeof output &
59
- ExtendOutputConfig;
60
-
61
- const ssgOptions: SSG = Array.isArray(ssg) ? ssg.pop() : ssg;
62
- // no ssg configuration, skip ssg render.
63
- if (!ssgOptions) {
64
- return;
65
- }
66
-
67
- const buildDir = path.join(appDirectory, outputPath as string);
68
- const routes = readJSONSpec(buildDir);
69
-
70
- // filter all routes not web
71
- const pageRoutes = routes.filter(route => !route.isApi);
72
- const apiRoutes = routes.filter(route => route.isApi);
73
-
74
- // if no web page route, skip ssg render
75
- if (pageRoutes.length === 0) {
76
- return;
77
- }
78
-
79
- const intermediateOptions = standardOptions(ssgOptions, entrypoints);
80
-
81
- if (!intermediateOptions) {
82
- return;
83
- }
84
-
85
- const ssgRoutes: SsgRoute[] = [];
86
- // each route will try to match the configuration
87
- pageRoutes.forEach(pageRoute => {
88
- const { entryName, entryPath } = pageRoute;
89
- const agreedRoutes = agreedRouteMap[entryName as string];
90
- let entryOptions = intermediateOptions[entryName as string];
91
-
92
- if (!agreedRoutes) {
93
- // default behavior for non-agreed route
94
- if (!entryOptions) {
95
- return;
96
- }
97
-
98
- // only add entry route if entryOptions is true
99
- if (entryOptions === true) {
100
- ssgRoutes.push({ ...pageRoute, output: entryPath });
101
- } else if (entryOptions.routes?.length > 0) {
102
- // if entryOptions is object and has routes options
103
- // add every route in options
104
- const { routes: enrtyRoutes, headers } = entryOptions;
105
- enrtyRoutes.forEach(route => {
106
- ssgRoutes.push(makeRoute(pageRoute, route, headers));
107
- });
108
- }
109
- } else {
110
- // Unless entryOptions is set to false
111
- // the default behavior is to add all file-based routes
112
- if (entryOptions === false) {
113
- return;
114
- }
115
-
116
- if (!entryOptions || entryOptions === true) {
117
- entryOptions = { preventDefault: [], routes: [], headers: {} };
118
- }
119
-
120
- const {
121
- preventDefault = [],
122
- routes: userRoutes = [],
123
- headers,
124
- } = entryOptions;
125
- // if the user sets the routes, then only add them
126
- if (userRoutes.length > 0) {
127
- userRoutes.forEach(route => {
128
- if (typeof route === 'string') {
129
- ssgRoutes.push(makeRoute(pageRoute, route, headers));
130
- } else if (Array.isArray(route.params)) {
131
- route.params.forEach(param => {
132
- ssgRoutes.push(
133
- makeRoute(
134
- pageRoute,
135
- { ...route, url: generatePath(route.url, param) },
136
- headers,
137
- ),
138
- );
139
- });
140
- } else {
141
- ssgRoutes.push(makeRoute(pageRoute, route, headers));
142
- }
143
- });
144
- } else {
145
- // otherwith add all except dynamic routes
146
- agreedRoutes
147
- .filter(route => !preventDefault.includes(route.path))
148
- .forEach(route => {
149
- if (!isDynamicUrl(route.path)) {
150
- ssgRoutes.push(makeRoute(pageRoute, route.path, headers));
151
- }
152
- });
153
- }
154
- }
155
- });
156
-
157
- if (ssgRoutes.length === 0) {
158
- return;
159
- }
160
-
161
- // currently SSG and SSR cannot be turned on at the same time、same route
162
- ssgRoutes.forEach((ssgRoute: SsgRoute) => {
163
- if (ssgRoute.isSSR) {
164
- const isOriginRoute = pageRoutes.some(
165
- pageRoute =>
166
- pageRoute.urlPath === ssgRoute.urlPath &&
167
- pageRoute.entryName === ssgRoute.entryName,
168
- );
169
-
170
- if (isOriginRoute) {
171
- throw new Error(
172
- `ssg can not using with ssr,url - ${
173
- ssgRoute.urlPath
174
- }, entry - ${ssgRoute.entryName!} `,
175
- );
176
- }
177
-
178
- logger.warn(
179
- `new ssg route ${
180
- ssgRoute.urlPath
181
- } is using ssr now,maybe from parent route ${ssgRoute.entryName!},close ssr`,
182
- );
183
- }
184
- ssgRoute.isSSR = false;
185
- ssgRoute.output = formatOutput(ssgRoute.output);
186
- });
187
-
188
- const htmlAry = await createServer(
189
- ssgRoutes,
190
- apiRoutes,
191
- resolvedConfig,
192
- appDirectory,
193
- );
194
-
195
- // write to dist file
196
- writeHtmlFile(htmlAry, ssgRoutes, buildDir);
197
-
198
- // format route info, side effect
199
- replaceRoute(ssgRoutes, pageRoutes);
200
-
201
- // write routes to spec file
202
- writeJSONSpec(buildDir, pageRoutes.concat(apiRoutes));
203
-
204
- logger.info('ssg Compiled successfully');
205
- },
206
- };
207
- }) as any,
208
- { name: '@modern-js/plugin-ssg' },
209
- ) as any;
package/src/libs/make.ts DELETED
@@ -1,45 +0,0 @@
1
- import path from 'path';
2
- import { ServerRoute as ModernRoute } from '@modern-js/types';
3
- import normalize from 'normalize-path';
4
- import { compile } from '../server/prerender';
5
- import { RouteOptions, SsgRoute } from '../types';
6
-
7
- export function makeRender(
8
- ssgRoutes: SsgRoute[],
9
- render: ReturnType<typeof compile>,
10
- port: number,
11
- ): Promise<string>[] {
12
- return ssgRoutes.map((ssgRoute: SsgRoute) =>
13
- render({
14
- url: ssgRoute.urlPath,
15
- headers: { host: `localhost:${port}`, ...ssgRoute.headers },
16
- connection: {},
17
- }),
18
- );
19
- }
20
-
21
- export function makeRoute(
22
- baseRoute: ModernRoute,
23
- route: string | RouteOptions,
24
- headers: Record<string, any> = {},
25
- ): SsgRoute {
26
- const { urlPath, entryPath } = baseRoute;
27
-
28
- if (typeof route === 'string') {
29
- return {
30
- ...baseRoute,
31
- urlPath: normalize(`${urlPath}${route}`) || '/',
32
- headers,
33
- output: path.join(entryPath, `..${route}`),
34
- };
35
- } else {
36
- return {
37
- ...baseRoute,
38
- urlPath: normalize(`${urlPath}${route.url}`) || '/',
39
- headers: { ...headers, ...route.headers },
40
- output: route.output
41
- ? path.normalize(route.output)
42
- : path.join(entryPath, `..${route.url}`),
43
- };
44
- }
45
- }
@@ -1,19 +0,0 @@
1
- import path from 'path';
2
- import { fs } from '@modern-js/utils';
3
- import { SsgRoute } from '../types';
4
-
5
- export function writeHtmlFile(
6
- htmlAry: string[],
7
- ssgRoutes: SsgRoute[],
8
- baseDir: string,
9
- ) {
10
- htmlAry.forEach((html: any, index: number) => {
11
- const ssgRoute = ssgRoutes[index];
12
- const filepath = path.join(baseDir, ssgRoute.output);
13
- if (!fs.existsSync(path.dirname(filepath))) {
14
- fs.ensureDirSync(path.dirname(filepath));
15
- }
16
-
17
- fs.writeFileSync(filepath, html);
18
- });
19
- }
@@ -1,42 +0,0 @@
1
- import normalize from 'normalize-path';
2
- import { ServerRoute as ModernRoute } from '@modern-js/types';
3
- import { SsgRoute } from '../types';
4
-
5
- export function exist(route: ModernRoute, pageRoutes: ModernRoute[]): number {
6
- return pageRoutes.slice().findIndex(pageRoute => {
7
- const urlEqual = normalize(pageRoute.urlPath) === normalize(route.urlPath);
8
- const entryEqual = pageRoute.entryName === route.entryName;
9
- if (urlEqual && entryEqual) {
10
- return true;
11
- }
12
- return false;
13
- });
14
- }
15
-
16
- export function replaceRoute(ssgRoutes: SsgRoute[], pageRoutes: ModernRoute[]) {
17
- // remove redundant fields and replace rendered entryPath
18
- const cleanSsgRoutes = ssgRoutes.map(ssgRoute => {
19
- const { output, headers, ...cleanSsgRoute } = ssgRoute;
20
- return Object.assign(
21
- cleanSsgRoute,
22
- output ? { entryPath: output } : {},
23
- ) as ModernRoute;
24
- });
25
-
26
- // all routes that need to be added and replaced
27
- const freshRoutes: ModernRoute[] = [];
28
- cleanSsgRoutes.forEach(ssgRoute => {
29
- const index = exist(ssgRoute, pageRoutes);
30
-
31
- if (index < 0) {
32
- // new route
33
- freshRoutes.push({ ...ssgRoute });
34
- } else {
35
- // overwrite original entry
36
- pageRoutes[index].entryPath = ssgRoute.entryPath;
37
- }
38
- });
39
-
40
- pageRoutes.push(...freshRoutes);
41
- return pageRoutes;
42
- }
package/src/libs/util.ts DELETED
@@ -1,127 +0,0 @@
1
- import path from 'path';
2
- import { ROUTE_SPEC_FILE, fs, isSingleEntry } from '@modern-js/utils';
3
- import { ServerRoute as ModernRoute } from '@modern-js/types';
4
- import { EntryPoint, MultiEntryOptions, SSG, SsgRoute } from '../types';
5
-
6
- export function formatOutput(filename: string) {
7
- const outputPath = path.extname(filename)
8
- ? filename
9
- : `${filename}/index.html`;
10
- return outputPath;
11
- }
12
-
13
- export function formatPath(str: string) {
14
- let addr = str;
15
- if (!addr || typeof addr !== 'string') {
16
- return addr;
17
- }
18
- if (addr.startsWith('.')) {
19
- addr = addr.slice(1);
20
- }
21
- if (!addr.startsWith('/')) {
22
- addr = `/${addr}`;
23
- }
24
- if (addr.endsWith('/') && addr !== '/') {
25
- addr = addr.slice(0, addr.length - 1);
26
- }
27
-
28
- return addr;
29
- }
30
-
31
- export function isDynamicUrl(url: string): boolean {
32
- return url.includes(':');
33
- }
34
-
35
- export function getUrlPrefix(route: SsgRoute, baseUrl: string | string[]) {
36
- let base = '';
37
- if (Array.isArray(baseUrl)) {
38
- const filters = baseUrl.filter(url => route.urlPath.includes(url));
39
- if (filters.length > 1) {
40
- const matched = filters.sort((a, b) => a.length - b.length)[0];
41
-
42
- // this should never happend
43
- if (!matched) {
44
- throw new Error('');
45
- }
46
- base = matched;
47
- }
48
- } else {
49
- base = baseUrl;
50
- }
51
-
52
- base = base === '/' ? '' : base;
53
- const entryName = route.entryName === 'main' ? '' : route.entryName;
54
- const prefix = `${base}/${entryName as string}`;
55
- return prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
56
- }
57
-
58
- // if no output, return default path for aggred-route(relative),
59
- // or thorw error for control-route
60
- export function getOutput(route: SsgRoute, base: string, agreed?: boolean) {
61
- const { output } = route;
62
- if (output) {
63
- return output;
64
- }
65
-
66
- if (agreed) {
67
- const urlWithoutBase = route.urlPath.replace(base, '');
68
- return urlWithoutBase.startsWith('/')
69
- ? urlWithoutBase.slice(1)
70
- : urlWithoutBase;
71
- }
72
-
73
- throw new Error(
74
- `routing must provide output when calling createPage(), check ${route.urlPath}`,
75
- );
76
- }
77
-
78
- export const readJSONSpec = (dir: string) => {
79
- const routeJSONPath = path.join(dir, ROUTE_SPEC_FILE);
80
- const routeJSON: {
81
- routes: ModernRoute[];
82
- } = require(routeJSONPath);
83
- const { routes } = routeJSON;
84
- return routes;
85
- };
86
-
87
- export const writeJSONSpec = (dir: string, routes: ModernRoute[]) => {
88
- const routeJSONPath = path.join(dir, ROUTE_SPEC_FILE);
89
- fs.writeJSONSync(routeJSONPath, { routes }, { spaces: 2 });
90
- };
91
-
92
- export const replaceWithAlias = (
93
- base: string,
94
- filePath: string,
95
- alias: string,
96
- ) => path.posix.join(alias, path.posix.relative(base, filePath));
97
-
98
- export const standardOptions = (ssgOptions: SSG, entrypoints: EntryPoint[]) => {
99
- if (ssgOptions === false) {
100
- return false;
101
- }
102
-
103
- if (ssgOptions === true) {
104
- return entrypoints.reduce((opt, entry) => {
105
- opt[entry.entryName] = ssgOptions;
106
- return opt;
107
- }, {} as MultiEntryOptions);
108
- } else if (typeof ssgOptions === 'object') {
109
- const isSingle = isSingleEntry(entrypoints);
110
-
111
- if (isSingle && typeof (ssgOptions as any).main === 'undefined') {
112
- return { main: ssgOptions } as MultiEntryOptions;
113
- } else {
114
- return ssgOptions as MultiEntryOptions;
115
- }
116
- } else if (typeof ssgOptions === 'function') {
117
- const intermediateOptions: MultiEntryOptions = {};
118
- for (const entrypoint of entrypoints) {
119
- const { entryName } = entrypoint;
120
- // Todo may be async function
121
- intermediateOptions[entryName] = ssgOptions(entryName);
122
- }
123
- return intermediateOptions;
124
- }
125
-
126
- return false;
127
- };
@@ -1 +0,0 @@
1
- export const CLOSE_SIGN = 'modern_close_server';
@@ -1,85 +0,0 @@
1
- import childProcess from 'child_process';
2
- import path from 'path';
3
- import { logger, SERVER_BUNDLE_DIRECTORY } from '@modern-js/utils';
4
- import { NormalizedConfig, useAppContext } from '@modern-js/core';
5
- import { ServerRoute as ModernRoute } from '@modern-js/types';
6
- import { SsgRoute } from '../types';
7
- import { CLOSE_SIGN } from './consts';
8
-
9
- export const createServer = (
10
- ssgRoutes: SsgRoute[],
11
- apiRoutes: ModernRoute[],
12
- options: NormalizedConfig,
13
- appDirectory: string,
14
- ): Promise<string[]> =>
15
- new Promise((resolve, reject) => {
16
- // this side of the shallow copy of a route for subsequent render processing, to prevent the modification of the current field
17
- // manually enable the server-side rendering configuration for all routes that require SSG
18
- const backup: ModernRoute[] = ssgRoutes.map(ssgRoute => ({
19
- ...ssgRoute,
20
- isSSR: true,
21
- bundle: `${SERVER_BUNDLE_DIRECTORY}/${ssgRoute.entryName as string}.js`,
22
- }));
23
-
24
- const total = backup.concat(apiRoutes);
25
-
26
- const cp = childProcess.fork(path.join(__dirname, 'process'), {
27
- cwd: appDirectory,
28
- silent: true,
29
- });
30
-
31
- const appContext = useAppContext();
32
- const serverPlugins = appContext.plugins
33
- .filter((p: any) => p.server)
34
- .map((p: any) => p.server);
35
- const plugins = serverPlugins.map((p: any) => p.name);
36
-
37
- cp.send(
38
- JSON.stringify({
39
- options,
40
- routes: total,
41
- appDirectory,
42
- plugins,
43
- }),
44
- );
45
-
46
- const htmlChunks: string[] = [];
47
- const htmlAry: string[] = [];
48
-
49
- cp.on('message', (chunk: string) => {
50
- if (chunk !== null) {
51
- htmlChunks.push(chunk);
52
- } else {
53
- const html = htmlChunks.join('');
54
- htmlAry.push(html);
55
- htmlChunks.length = 0;
56
- }
57
-
58
- if (htmlAry.length === backup.length) {
59
- cp.send(CLOSE_SIGN);
60
- resolve(htmlAry);
61
- }
62
- });
63
-
64
- cp.stderr!.on('data', chunk => {
65
- const str = chunk.toString();
66
- if (str.includes('Error')) {
67
- logger.error(str);
68
- reject(new Error('ssg render failed'));
69
- cp.kill('SIGKILL');
70
- } else {
71
- logger.info(str.replace(/[^\S\n]+/g, ' '));
72
- }
73
- });
74
-
75
- cp.stdout!.on('data', chunk => {
76
- const str = chunk.toString();
77
- if (str.includes('Error')) {
78
- logger.error(str);
79
- reject(new Error('ssg render failed'));
80
- cp.kill('SIGKILL');
81
- } else {
82
- logger.info(str.replace(/[^\S\n]+/g, ' '));
83
- }
84
- });
85
- });
@@ -1,49 +0,0 @@
1
- import EventEmitter from 'events';
2
- import { IncomingMessage, ServerResponse } from 'http';
3
- import { Readable } from 'stream';
4
- import httpMocks from 'node-mocks-http';
5
-
6
- export type Options = {
7
- url: string;
8
- headers: {
9
- host: string;
10
- [key: string]: string;
11
- };
12
- [propName: string]: any;
13
- };
14
-
15
- export const compile =
16
- (requestHandler: (req: IncomingMessage, res: ServerResponse) => void) =>
17
- (options: Options, extend = {}): Promise<string> =>
18
- new Promise((resolve, reject) => {
19
- const req = httpMocks.createRequest({
20
- ...options,
21
- eventEmitter: Readable,
22
- });
23
- const res = httpMocks.createResponse({ eventEmitter: EventEmitter });
24
-
25
- Object.assign(req, extend);
26
- const proxyRes = new Proxy(res, {
27
- get(obj: any, prop: any) {
28
- if (typeof prop === 'symbol' && !obj[prop]) {
29
- return null;
30
- }
31
- return obj[prop];
32
- },
33
- });
34
-
35
- res.on('finish', () => {
36
- if (res.statusCode !== 200) {
37
- reject(new Error(res.statusMessage));
38
- } else {
39
- resolve(res._getData());
40
- }
41
- });
42
-
43
- res.on('error', (e: Error) => reject(e));
44
- try {
45
- requestHandler(req, proxyRes);
46
- } catch (e) {
47
- reject(e);
48
- }
49
- });
@@ -1,94 +0,0 @@
1
- import Server from '@modern-js/server';
2
- import { ServerRoute as ModernRoute } from '@modern-js/types';
3
- import portfinder from 'portfinder';
4
- import { NormalizedConfig } from '@modern-js/core';
5
- import { compatRequire } from '@modern-js/utils';
6
- import { makeRender } from '../libs/make';
7
- import { SsgRoute } from '../types';
8
- import { compile as createRender } from './prerender';
9
- import { CLOSE_SIGN } from './consts';
10
-
11
- type Then<T> = T extends PromiseLike<infer U> ? U : T;
12
-
13
- type ModernServer = Then<ReturnType<typeof Server>>;
14
-
15
- const safetyRequire = (filename: string, base: string) => {
16
- try {
17
- return compatRequire(
18
- require.resolve(`${filename}/server`, { paths: [base] }),
19
- );
20
- } catch (e) {
21
- return compatRequire(require.resolve(filename, { paths: [base] }));
22
- }
23
- };
24
-
25
- process.on('message', async (chunk: string) => {
26
- if (chunk === CLOSE_SIGN) {
27
- // eslint-disable-next-line no-process-exit
28
- process.exit();
29
- }
30
-
31
- const context = JSON.parse(chunk as any);
32
- const {
33
- routes,
34
- options,
35
- appDirectory,
36
- plugins,
37
- }: {
38
- routes: ModernRoute[];
39
- options: NormalizedConfig;
40
- appDirectory: string;
41
- plugins: string[];
42
- } = context;
43
-
44
- const instances = plugins.map(plugin => safetyRequire(plugin, appDirectory));
45
-
46
- let modernServer: ModernServer | null = null;
47
- try {
48
- const { server } = options;
49
-
50
- // start server in default port
51
- const defaultPort = Number(process.env.PORT) || server.port;
52
- portfinder.basePort = defaultPort!;
53
- const port = await portfinder.getPortPromise();
54
-
55
- modernServer = await Server({
56
- pwd: appDirectory,
57
- config: options,
58
- routes,
59
- staticGenerate: true,
60
- plugins: instances,
61
- });
62
-
63
- // listen just for bff request in ssr page
64
- modernServer.listen(port, async (err: Error) => {
65
- if (err) {
66
- throw err;
67
- }
68
-
69
- if (!modernServer) {
70
- return;
71
- }
72
-
73
- // get server handler, render to ssr
74
- const render = createRender(modernServer.getRequestHandler());
75
- const renderPromiseAry = makeRender(
76
- routes.filter(route => !route.isApi) as SsgRoute[],
77
- render,
78
- port,
79
- );
80
-
81
- // eslint-disable-next-line promise/no-promise-in-callback
82
- const htmlAry = await Promise.all(renderPromiseAry);
83
- htmlAry.forEach((html: string) => {
84
- process.send!(html);
85
- process.send!(null);
86
- });
87
-
88
- modernServer.close();
89
- });
90
- } catch (e) {
91
- modernServer?.close();
92
- throw e;
93
- }
94
- });
package/src/types.ts DELETED
@@ -1,51 +0,0 @@
1
- import { ServerRoute as ModernRoute } from '@modern-js/types';
2
-
3
- export type AgreedRoute = {
4
- path: string;
5
- component: string;
6
- _component: string;
7
- exact: boolean;
8
- };
9
-
10
- export type EntryPoint = {
11
- entryName: string;
12
- entry: string;
13
- };
14
-
15
- export type AgreedRouteMap = {
16
- [propNames: string]: AgreedRoute[];
17
- };
18
-
19
- export type SsgRoute = ModernRoute & {
20
- output: string;
21
- headers?: Record<string, string>;
22
- };
23
-
24
- export type RouteOptions =
25
- | string
26
- | {
27
- url: string;
28
- output?: string;
29
- params?: Record<string, any>[];
30
- headers?: Record<string, any>;
31
- };
32
-
33
- export type SingleEntryOptions =
34
- | boolean
35
- | {
36
- preventDefault?: string[];
37
- headers?: Record<string, any>;
38
- routes: RouteOptions[];
39
- };
40
-
41
- export type MultiEntryOptions = Record<string, SingleEntryOptions>;
42
-
43
- export type SSG =
44
- | boolean
45
- | SingleEntryOptions
46
- | MultiEntryOptions
47
- | ((entryName: string) => SingleEntryOptions);
48
-
49
- export type ExtendOutputConfig = {
50
- ssg: SSG;
51
- };