Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(react): generate correctly when --js is used for module federation host/remote #20119

Merged
merged 7 commits into from
Feb 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,8 @@
"e2eTestRunner": {
"type": "string",
"enum": ["cypress", "playwright", "none"],
"description": "Test runner to use for end to end (e2e) tests.",
"description": "Test runner to use for end to end (E2E) tests.",
"x-prompt": "Which E2E test runner would you like to use?",
"default": "cypress"
},
"host": {
Expand Down
5 changes: 3 additions & 2 deletions docs/generated/packages/react/generators/host.json
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,8 @@
"e2eTestRunner": {
"type": "string",
"enum": ["cypress", "playwright", "none"],
"description": "Test runner to use for end to end (e2e) tests.",
"description": "Test runner to use for end to end (E2E) tests.",
"x-prompt": "Which E2E test runner would you like to use?",
"default": "cypress"
},
"tags": {
Expand Down Expand Up @@ -164,7 +165,7 @@
},
"typescriptConfiguration": {
"type": "boolean",
"description": "Whether the module federation configuration and webpack configuration files should use TS.",
"description": "Whether the module federation configuration and webpack configuration files should use TS. When --js is used, this flag is ignored.",
"default": true
}
},
Expand Down
5 changes: 3 additions & 2 deletions docs/generated/packages/react/generators/remote.json
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,8 @@
"e2eTestRunner": {
"type": "string",
"enum": ["cypress", "playwright", "none"],
"description": "Test runner to use for end to end (e2e) tests.",
"description": "Test runner to use for end to end (E2E) tests.",
"x-prompt": "Which E2E test runner would you like to use?",
"default": "cypress"
},
"tags": {
Expand Down Expand Up @@ -163,7 +164,7 @@
},
"typescriptConfiguration": {
"type": "boolean",
"description": "Whether the module federation configuration and webpack configuration files should use TS.",
"description": "Whether the module federation configuration and webpack configuration files should use TS. When --js is used, this flag is ignored.",
"default": true
}
},
Expand Down
167 changes: 110 additions & 57 deletions e2e/react-module-federation/src/react-module-federation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,51 +20,85 @@ import { join } from 'path';
import { createTreeWithEmptyWorkspace } from 'nx/src/devkit-testing-exports';

describe('React Module Federation', () => {
let proj: string;
let tree: Tree;

beforeAll(() => {
tree = createTreeWithEmptyWorkspace();
proj = newProject({ packages: ['@nx/react'] });
newProject({ packages: ['@nx/react'] });
});

afterAll(() => cleanupProject());

describe('Default Configuration', () => {
it('should generate host and remote apps', async () => {
const shell = uniq('shell');
const remote1 = uniq('remote1');
const remote2 = uniq('remote2');
const remote3 = uniq('remote3');

// Since we are using a single-file server for the remotes
const defaultRemotePort = 4201;
it.each`
js
${false}
${true}
`(
'should generate host and remote apps',
async ({ js }) => {
const shell = uniq('shell');
const remote1 = uniq('remote1');
const remote2 = uniq('remote2');
const remote3 = uniq('remote3');

// Since we are using a single-file server for the remotes
const defaultRemotePort = 4201;

runCLI(
`generate @nx/react:host ${shell} --remotes=${remote1},${remote2},${remote3} --style=css --no-interactive --skipFormat --js=${js}`
);

runCLI(
`generate @nx/react:host ${shell} --remotes=${remote1},${remote2},${remote3} --style=css --no-interactive --skipFormat`
);
checkFilesExist(
`apps/${shell}/module-federation.config.${js ? 'js' : 'ts'}`
);
checkFilesExist(
`apps/${remote1}/module-federation.config.${js ? 'js' : 'ts'}`
);
checkFilesExist(
`apps/${remote2}/module-federation.config.${js ? 'js' : 'ts'}`
);
checkFilesExist(
`apps/${remote3}/module-federation.config.${js ? 'js' : 'ts'}`
);

checkFilesExist(`apps/${shell}/module-federation.config.ts`);
checkFilesExist(`apps/${remote1}/module-federation.config.ts`);
checkFilesExist(`apps/${remote2}/module-federation.config.ts`);
checkFilesExist(`apps/${remote3}/module-federation.config.ts`);
await expect(runCLIAsync(`test ${shell}`)).resolves.toMatchObject({
combinedOutput: expect.stringContaining(
'Test Suites: 1 passed, 1 total'
),
});

await expect(runCLIAsync(`test ${shell}`)).resolves.toMatchObject({
combinedOutput: expect.stringContaining(
'Test Suites: 1 passed, 1 total'
),
});
if (js) {
updateFile(
`apps/${shell}/webpack.config.js`,
stripIndents`
const { composePlugins, withNx } = require('@nx/webpack');
const { withReact } = require('@nx/react');
const { withModuleFederation } = require('@nx/react/module-federation');

const baseConfig = require('./module-federation.config');

const config = {
...baseConfig,
remotes: [
'${remote1}',
['${remote2}', 'http://localhost:${defaultRemotePort}/${remote2}/remoteEntry.js'],
['${remote3}', 'http://localhost:${defaultRemotePort}/${remote3}/remoteEntry.js'],
],
};

updateFile(
`apps/${shell}/webpack.config.ts`,
stripIndents`
import { composePlugins, withNx, ModuleFederationConfig } from '@nx/webpack';
// Nx plugins for webpack to build config object from Nx options and context.
module.exports = composePlugins(withNx(), withReact(), withModuleFederation(config));
`
);
} else {
updateFile(
`apps/${shell}/webpack.config.ts`,
stripIndents`
import { composePlugins, withNx } from '@nx/webpack';
import { withReact } from '@nx/react';
import { withModuleFederation } from '@nx/react/module-federation';

import baseConfig from './module-federation.config';

const config: ModuleFederationConfig = {
const config = {
...baseConfig,
remotes: [
'${remote1}',
Expand All @@ -74,13 +108,14 @@ describe('React Module Federation', () => {
};

// Nx plugins for webpack to build config object from Nx options and context.
module.exports = composePlugins(withNx(), withReact(), withModuleFederation(config));
export default composePlugins(withNx(), withReact(), withModuleFederation(config));
`
);
);
}

updateFile(
`apps/${shell}-e2e/src/integration/app.spec.ts`,
stripIndents`
updateFile(
`apps/${shell}-e2e/src/integration/app.spec.${js ? 'js' : 'ts'}`,
stripIndents`
import { getGreeting } from '../support/app.po';

describe('shell app', () => {
Expand All @@ -105,34 +140,53 @@ describe('React Module Federation', () => {
});
});
`
);

if (runE2ETests()) {
const e2eResultsSwc = await runCommandUntil(
`e2e ${shell}-e2e --no-watch --verbose`,
(output) => output.includes('All specs passed!')
);

await killProcessAndPorts(
e2eResultsSwc.pid,
readPort(shell),
defaultRemotePort
);
[shell, remote1, remote2, remote3].forEach((app) => {
['development', 'production'].forEach(async (configuration) => {
const cliOutput = runCLI(`run ${app}:build:${configuration}`);
expect(cliOutput).toContain('Successfully ran target');
});
});

const e2eResultsTsNode = await runCommandUntil(
`e2e ${shell}-e2e --no-watch --verbose`,
(output) => output.includes('All specs passed!'),
{
env: { NX_PREFER_TS_NODE: 'true' },
}
const serveResult = await runCommandUntil(`serve ${shell}`, (output) =>
output.includes(`http://localhost:${readPort(shell)}`)
);

await killProcessAndPorts(
e2eResultsTsNode.pid,
serveResult.pid,
readPort(shell),
defaultRemotePort
);
}
}, 500_000);

if (runE2ETests()) {
const e2eResultsSwc = await runCommandUntil(
`e2e ${shell}-e2e --no-watch --verbose`,
(output) => output.includes('All specs passed!')
);

await killProcessAndPorts(
e2eResultsSwc.pid,
readPort(shell),
defaultRemotePort
);

const e2eResultsTsNode = await runCommandUntil(
`e2e ${shell}-e2e --no-watch --verbose`,
(output) => output.includes('All specs passed!'),
{
env: { NX_PREFER_TS_NODE: 'true' },
}
);
await killProcessAndPorts(
e2eResultsTsNode.pid,
readPort(shell),
defaultRemotePort
);
}
},
500_000
);

it('should generate host and remote apps with ssr', async () => {
const shell = uniq('shell');
Expand Down Expand Up @@ -865,8 +919,7 @@ describe('React Module Federation', () => {

describe('Dynamic Module Federation', () => {
beforeAll(() => {
tree = createTreeWithEmptyWorkspace();
proj = newProject({ packages: ['@nx/react'] });
newProject({ packages: ['@nx/react'] });
});

afterAll(() => cleanupProject());
Expand Down
14 changes: 12 additions & 2 deletions packages/cypress/plugins/cypress-preset.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { workspaceRoot } from '@nx/devkit';
import { dirname, join, relative } from 'path';
import { lstatSync } from 'fs';
import { existsSync, lstatSync } from 'fs';

import vitePreprocessor from '../src/plugins/preprocessor-vite';
import { NX_PLUGIN_OPTIONS } from '../src/utils/constants';
Expand Down Expand Up @@ -102,12 +102,22 @@ export function nxE2EPreset(
) {
const basePath = options?.cypressDir || 'src';

const dir = dirname(pathToConfig);
let supportFile: undefined | string = undefined;
for (const f of ['e2e.ts', 'e2e.js']) {
const candidate = join(dir, basePath, 'support', f);
if (existsSync(candidate)) {
supportFile = candidate;
break;
}
}

const baseConfig: any /*Cypress.EndToEndConfigOptions & {
[NX_PLUGIN_OPTIONS]: unknown;
}*/ = {
...nxBaseCypressPreset(pathToConfig),
fileServerFolder: '.',
supportFile: `${basePath}/support/e2e.{js,ts}`,
supportFile,
specPattern: `${basePath}/**/*.cy.{js,jsx,ts,tsx}`,
fixturesFolder: `${basePath}/fixtures`,

Expand Down
3 changes: 2 additions & 1 deletion packages/react/src/generators/application/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { NormalizedSchema, Schema } from './schema';
import { createApplicationFiles } from './lib/create-application-files';
import { updateSpecConfig } from './lib/update-jest-config';
import { normalizeOptions } from './lib/normalize-options';
import { addProject, maybeJs } from './lib/add-project';
import { addProject } from './lib/add-project';
import { addJest } from './lib/add-jest';
import { addRouting } from './lib/add-routing';
import { setDefaults } from './lib/set-defaults';
Expand All @@ -27,6 +27,7 @@ import {
nxRspackVersion,
nxVersion,
} from '../../utils/versions';
import { maybeJs } from '../../utils/maybe-js';
import { installCommonDependencies } from './lib/install-common-dependencies';
import { extractTsConfigBase } from '../../utils/create-ts-config';
import { addSwcDependencies } from '@nx/js/src/utils/swc/add-swc-dependencies';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
Tree,
} from '@nx/devkit';
import { hasWebpackPlugin } from '../../../utils/has-webpack-plugin';
import { maybeJs } from '../../../utils/maybe-js';

export function addProject(host: Tree, options: NormalizedSchema) {
const project: ProjectConfiguration = {
Expand All @@ -31,12 +32,6 @@ export function addProject(host: Tree, options: NormalizedSchema) {
});
}

export function maybeJs(options: NormalizedSchema, path: string): string {
return options.js && (path.endsWith('.ts') || path.endsWith('.tsx'))
? path.replace(/\.tsx?$/, '.js')
: path;
}

function createBuildTarget(options: NormalizedSchema): TargetConfiguration {
return {
executor: '@nx/webpack:webpack',
Expand Down
13 changes: 4 additions & 9 deletions packages/react/src/generators/application/lib/add-routing.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { addInitialRoutes } from '../../../utils/ast-utils';
import { NormalizedSchema } from '../schema';
import { reactRouterDomVersion } from '../../../utils/versions';
import {
joinPathFragments,
Tree,
applyChangesToString,
addDependenciesToPackageJson,
} from '@nx/devkit';
import { ensureTypescript } from '@nx/js/src/utils/typescript/ensure-typescript';
import { addInitialRoutes } from '../../../utils/ast-utils';
import { reactRouterDomVersion } from '../../../utils/versions';
import { maybeJs } from '../../../utils/maybe-js';
import { NormalizedSchema } from '../schema';

let tsModule: typeof import('typescript');

Expand Down Expand Up @@ -47,9 +48,3 @@ export function addRouting(host: Tree, options: NormalizedSchema) {

return () => {};
}

function maybeJs(options: NormalizedSchema, path: string): string {
return options.js && (path.endsWith('.ts') || path.endsWith('.tsx'))
? path.replace(/\.tsx?$/, '.js')
: path;
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,16 @@ import {
Tree,
writeJson,
} from '@nx/devkit';
import { WithNxOptions } from '@nx/webpack';
import { getRelativePathToRootTsConfig } from '@nx/js';
import { join } from 'path';
import { createTsConfig } from '../../../utils/create-ts-config';
import { getInSourceVitestTestsTemplate } from '../../../utils/get-in-source-vitest-tests-template';
import { NormalizedSchema } from '../schema';
import { getAppTests } from './get-app-tests';
import { maybeJs } from './add-project';
import { maybeJs } from '../../../utils/maybe-js';
import { WithReactOptions } from '../../../../plugins/with-react';
import { WithNxOptions } from '@nx/webpack';
import { hasWebpackPlugin } from '../../../utils/has-webpack-plugin';
import { NormalizedSchema } from '../schema';
import { getAppTests } from './get-app-tests';

export function createApplicationFiles(host: Tree, options: NormalizedSchema) {
let styleSolutionSpecificAppFiles: string;
Expand Down
Loading