Skip to content

Commit

Permalink
feat(react): add SSR host generator
Browse files Browse the repository at this point in the history
  • Loading branch information
jaysoo authored and Jack Hsu committed Nov 28, 2022
1 parent d312a44 commit 88fdca2
Show file tree
Hide file tree
Showing 13 changed files with 270 additions and 102 deletions.
2 changes: 1 addition & 1 deletion packages/react/src/generators/application/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { SupportedStyles } from '../../../typings/style';
export interface Schema {
name: string;
style: SupportedStyles;
skipFormat: boolean;
skipFormat?: boolean;
directory?: string;
tags?: string;
unitTestRunner?: 'jest' | 'vitest' | 'none';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// @ts-check

/**
* @type {import('@nrwl/devkit').ModuleFederationConfig}
**/
const moduleFederationConfig = {
name: '<%= projectName %>',
remotes: [
<% remotes.forEach(function(r) {%> "<%= r.fileName %>", <% }); %>
],
};

module.exports = moduleFederationConfig;
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const { withModuleFederationForSSR } = require('@nrwl/react/module-federation');
const baseConfig = require("./module-federation.server.config");

const defaultConfig = {
...baseConfig
};

module.exports = withModuleFederationForSSR(defaultConfig);
60 changes: 60 additions & 0 deletions packages/react/src/generators/host/host.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import type { Tree } from '@nrwl/devkit';
import { readJson } from '@nrwl/devkit';
import { createTreeWithEmptyWorkspace } from '@nrwl/devkit/testing';
import hostGenerator from './host';
import { Linter } from '@nrwl/linter';

describe('hostGenerator', () => {
let tree: Tree;

beforeEach(() => {
tree = createTreeWithEmptyWorkspace({ layout: 'apps-libs' });
});

it('should generate host files and configs', async () => {
await hostGenerator(tree, {
name: 'test',
style: 'css',
linter: Linter.None,
unitTestRunner: 'none',
e2eTestRunner: 'none',
});

expect(tree.exists('apps/test/tsconfig.json'));
expect(tree.exists('apps/test/webpack.config.prod.js'));
expect(tree.exists('apps/test/webpack.config.js'));
expect(tree.exists('apps/test/src/bootstrap.tsx'));
expect(tree.exists('apps/test/src/main.ts'));
expect(tree.exists('apps/test/src/remotes.d.ts'));
});

it('should generate host files and configs for SSR', async () => {
await hostGenerator(tree, {
name: 'test',
ssr: true,
style: 'css',
linter: Linter.None,
unitTestRunner: 'none',
e2eTestRunner: 'none',
});

expect(tree.exists('apps/test/tsconfig.json'));
expect(tree.exists('apps/test/webpack.config.prod.js'));
expect(tree.exists('apps/test/webpack.config.server.js'));
expect(tree.exists('apps/test/webpack.config.js'));
expect(tree.exists('apps/test/src/main.server.tsx'));
expect(tree.exists('apps/test/src/bootstrap.tsx'));
expect(tree.exists('apps/test/src/main.ts'));
expect(tree.exists('apps/test/src/remotes.d.ts'));

expect(readJson(tree, 'apps/test/tsconfig.server.json')).toEqual({
compilerOptions: {
outDir: '../../out-tsc/server',
target: 'es2019',
types: ['node'],
},
extends: './tsconfig.app.json',
files: ['src/main.server.tsx', 'server.ts'],
});
});
});
44 changes: 37 additions & 7 deletions packages/react/src/generators/host/host.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
import { formatFiles, GeneratorCallback, Tree } from '@nrwl/devkit';
import {
addDependenciesToPackageJson,
formatFiles,
GeneratorCallback,
joinPathFragments,
readProjectConfiguration,
Tree,
updateProjectConfiguration,
} from '@nrwl/devkit';

import applicationGenerator from '../application/application';
import { normalizeOptions } from '../application/lib/normalize-options';
Expand All @@ -9,7 +17,9 @@ import { updateModuleFederationE2eProject } from './lib/update-module-federation
import { Schema } from './schema';
import remoteGenerator from '../remote/remote';
import { runTasksInSerial } from '@nrwl/workspace/src/utilities/run-tasks-in-serial';
import { addSsr } from './lib/add-ssr';
import { addSsrFiles } from './lib/add-ssr-files';
import setupSsrGenerator from '../setup-ssr/setup-ssr';
import { moduleFederationNodeVersion } from '@nrwl/react/src/utils/versions';

export async function hostGenerator(host: Tree, schema: Schema) {
const tasks: GeneratorCallback[] = [];
Expand All @@ -24,11 +34,6 @@ export async function hostGenerator(host: Tree, schema: Schema) {
});
tasks.push(initTask);

if (options.ssr) {
let ssrInstallTask = await addSsr(host, options, options.projectName);
tasks.push(ssrInstallTask);
}

const remotesWithPorts: { name: string; port: number }[] = [];

if (schema.remotes) {
Expand All @@ -53,6 +58,31 @@ export async function hostGenerator(host: Tree, schema: Schema) {
updateModuleFederationProject(host, options);
updateModuleFederationE2eProject(host, options);

if (options.ssr) {
const setupSsrTask = await setupSsrGenerator(host, {
project: options.projectName,
});
tasks.push(setupSsrTask);

const ssrInstallTask = addDependenciesToPackageJson(
host,
{
'@module-federation/node': moduleFederationNodeVersion,
},
{}
);
tasks.push(ssrInstallTask);

await addSsrFiles(host, options, options.projectName, remotesWithPorts);

const projectConfig = readProjectConfiguration(host, options.projectName);
projectConfig.targets.server.options.webpackConfig = joinPathFragments(
projectConfig.root,
'webpack.server.config.js'
);
updateProjectConfiguration(host, options.projectName, projectConfig);
}

if (!options.skipFormat) {
await formatFiles(host);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,17 @@ export function addModuleFederationFiles(
join(options.appProjectRoot, 'src/bootstrap.tsx')
);

// New entry file is created here.
generateFiles(
host,
join(__dirname, `../files/module-federation`),
join(__dirname, `../files/common`),
options.appProjectRoot,
templateVariables
);

// New entry file is created here.
generateFiles(
host,
join(__dirname, `../files/common`),
join(__dirname, `../files/module-federation`),
options.appProjectRoot,
templateVariables
);
Expand Down
51 changes: 51 additions & 0 deletions packages/react/src/generators/host/lib/add-ssr-files.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import type { GeneratorCallback, Tree } from '@nrwl/devkit';
import {
addDependenciesToPackageJson,
generateFiles,
joinPathFragments,
names,
readProjectConfiguration,
} from '@nrwl/devkit';
import type { Schema } from '../schema';
import { moduleFederationNodeVersion } from '../../../utils/versions';
import { runTasksInSerial } from '@nrwl/workspace/src/utilities/run-tasks-in-serial';
import { normalizeProjectName } from '@nrwl/react/src/generators/application/lib/normalize-options';

export async function addSsrFiles(
tree: Tree,
options: Schema,
appName: string,
defaultRemoteManifest: { name: string; port: number }[]
) {
const tasks: GeneratorCallback[] = [];
const project = readProjectConfiguration(tree, appName);

generateFiles(
tree,
joinPathFragments(__dirname, '../files/module-federation-ssr'),
project.root,
{
...options,
remotes: defaultRemoteManifest.map(({ name, port }) => {
const remote = normalizeProjectName({ ...options, name });
return {
...names(remote),
port,
};
}),
appName,
tmpl: '',
}
);

const installTask = addDependenciesToPackageJson(
tree,
{
'@module-federation/node': moduleFederationNodeVersion,
},
{}
);
tasks.push(installTask);

return runTasksInSerial(...tasks);
}
69 changes: 0 additions & 69 deletions packages/react/src/generators/host/lib/add-ssr.ts

This file was deleted.

2 changes: 1 addition & 1 deletion packages/react/src/generators/host/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export interface Schema {
pascalCaseFiles?: boolean;
remotes?: string[];
setParserOptionsProject?: boolean;
skipFormat: boolean;
skipFormat?: boolean;
skipWorkspaceJson?: boolean;
ssr?: boolean;
standaloneConfig?: boolean;
Expand Down
18 changes: 11 additions & 7 deletions packages/react/src/generators/setup-ssr/files/server.ts__tmpl__
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
import * as path from 'path';
import express from 'express';
import cors from 'cors';

import { handleRequest } from './src/main.server';
import * as path from 'path';

const port = process.env['port'] || 4200;
const app = express();

const browserDist = path.join(process.cwd(), '<%= browserBuildOutputPath %>');
const indexPath =path.join(browserDist, 'index.html');

app.get(
'*.*',
express.static(browserDist, {
maxAge: '1y',
})
);
app.use(cors());

app.get(
'*.*',
express.static(browserDist, {
maxAge: '1y',
})
);

app.use('*', handleRequest(indexPath));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
"node"
]
},
"include": [
"files": [
"src/main.server.tsx",
"server.ts",
"server.ts"
]
}
Loading

0 comments on commit 88fdca2

Please sign in to comment.