Skip to content

Commit

Permalink
fix(nextjs): Custom server should work with Crystal
Browse files Browse the repository at this point in the history
  • Loading branch information
ndcunningham committed Feb 9, 2024
1 parent 81410e4 commit 200710a
Show file tree
Hide file tree
Showing 6 changed files with 82 additions and 24 deletions.
34 changes: 34 additions & 0 deletions e2e/next-core/src/next.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,40 @@ describe('Next.js Applications', () => {
checkExport: false,
});
}, 300_000);

it('should support --custom-server flag (swc)', async () => {
const appName = uniq('app');

runCLI(`generate @nx/next:app ${appName} --no-interactive --custom-server`);

checkFilesExist(`apps/${appName}/server/main.ts`);

const result = runCLI(`build ${appName}`);

checkFilesExist(`dist/apps/${appName}/server/main.js`);

expect(result).toContain(
`Successfully ran target build for project ${appName}`
);
}, 300_000);

it('should support --custom-server flag (tsc)', async () => {
const appName = uniq('app');

runCLI(
`generate @nx/next:app ${appName} --swc=false --no-interactive --custom-server`
);

checkFilesExist(`apps/${appName}/server/main.ts`);

const result = runCLI(`build ${appName}`);

checkFilesExist(`dist/apps/${appName}/server/main.js`);

expect(result).toContain(
`Successfully ran target build for project ${appName}`
);
}, 300_000);
});

function getData(port, path = ''): Promise<any> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,7 @@ import { applicationGenerator } from '../application/application';
describe('app', () => {
let tree: Tree;

let originalEnv: string;
beforeAll(() => {
originalEnv = process.env.NX_ADD_PLUGINS;
process.env.NX_ADD_PLUGINS = 'false';
});
afterAll(() => {
process.env.NX_ADD_PLUGINS = originalEnv;
});

beforeEach(() => {
tree = createTreeWithEmptyWorkspace();
});

Expand Down
41 changes: 31 additions & 10 deletions packages/next/src/generators/custom-server/custom-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
offsetFromRoot,
readProjectConfiguration,
updateProjectConfiguration,
readNxJson,
} from '@nx/devkit';
import { CustomServerSchema } from './schema';
import { join } from 'path';
Expand All @@ -17,24 +18,36 @@ export async function customServerGenerator(
) {
const project = readProjectConfiguration(host, options.project);

const nxJson = readNxJson(host);
const hasPlugin = nxJson.plugins?.some((p) =>
typeof p === 'string'
? p === '@nx/next/plugin'
: p.plugin === '@nx/next/plugin'
);

if (
project.targets?.build?.executor !== '@nx/next:build' &&
project.targets?.build?.executor !== '@nrwl/next:build'
project.targets?.build?.executor !== '@nrwl/next:build' &&
!hasPlugin
) {
logger.error(
`Project ${options.project} is not a Next.js project. Did you generate it with "nx g @nx/next:app"?`
);
return;
}

const outputPath = project.targets?.build?.options?.outputPath;
// In Nx 18 next artifacts are inside the project root .next/ & dist/ (for custom server)
const outputPath = hasPlugin
? `dist/${project.root}`
: project.targets?.build?.options?.outputPath;
const root = project.root;

if (
!root ||
!outputPath ||
!project.targets?.build?.configurations?.development ||
!project.targets?.build?.configurations?.production
(!root ||
!outputPath ||
!project.targets?.build?.configurations?.development ||
!project.targets?.build?.configurations?.production) &&
!hasPlugin
) {
logger.error(
`Project ${options.project} has invalid config. Did you generate it with "nx g @nx/next:app"?`
Expand All @@ -54,15 +67,23 @@ export async function customServerGenerator(

generateFiles(host, join(__dirname, 'files'), project.root, {
...options,
hasPlugin,
projectPathFromRoot: `../../${offsetFromRoot(project.root)}${project.root}`,
offsetFromRoot: offsetFromRoot(project.root),
projectRoot: project.root,
tmpl: '',
});

project.targets.build.dependsOn = ['build-custom-server'];
project.targets.serve.options.customServerTarget = `${options.project}:serve-custom-server`;
project.targets.serve.configurations.development.customServerTarget = `${options.project}:serve-custom-server:development`;
project.targets.serve.configurations.production.customServerTarget = `${options.project}:serve-custom-server:production`;
if (!hasPlugin) {
project.targets.build.dependsOn = ['build-custom-server'];
project.targets.serve.options.customServerTarget = `${options.project}:serve-custom-server`;
project.targets.serve.configurations.development.customServerTarget = `${options.project}:serve-custom-server:development`;
project.targets.serve.configurations.production.customServerTarget = `${options.project}:serve-custom-server:production`;
} else {
project.targets['build'] = {
dependsOn: ['^build', 'build-custom-server'],
};
}

project.targets['build-custom-server'] = {
executor: options.compiler === 'tsc' ? '@nx/js:tsc' : '@nx/js:swc',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@
* This is only a minimal custom server to get started.
* You may want to consider using Express or another server framework, and enable security features such as CORS.
*
* For more examples, see the Next.js repo:
* - Express: https://github.com/vercel/next.js/tree/canary/examples/custom-server-express
* - Hapi: https://github.com/vercel/next.js/tree/canary/examples/custom-server-hapi
* For an example, see the Next.js repo:
* Node - https://github.com/vercel/next.js/blob/canary/examples/custom-server
*/
import { createServer } from 'http';
import { parse } from 'node:url';
Expand All @@ -15,7 +14,8 @@ import next from 'next';
// - The environment variable is set by `@nx/next:server` when running the dev server.
// - The fallback `__dirname` is for production builds.
// - Feel free to change this to suit your needs.
const dir = process.env.NX_NEXT_DIR || path.join(__dirname, '..');

const dir = process.env.NX_NEXT_DIR || <%- hasPlugin ? `path.join(__dirname, '${projectPathFromRoot}')` : `path.join(__dirname, '..')`; %>
const dev = process.env.NODE_ENV === 'development';

// HTTP Server options:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
"module": "commonjs",
"noEmit": false,
"incremental": true,
<% if(hasPlugin && compiler === 'tsc') { %>
"tsBuildInfoFile": "<%= offsetFromRoot %>tmp/buildcache/<%= projectRoot %>/server",
<% } %>
"types": [
"node"
]
Expand Down
12 changes: 11 additions & 1 deletion packages/next/src/utils/add-swc-to-custom-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
installPackagesTask,
joinPathFragments,
readJson,
updateJson,
} from '@nx/devkit';
import { swcCliVersion, swcCoreVersion, swcNodeVersion } from './versions';
import { addSwcConfig } from '@nx/js/src/utils/swc/add-swc-config';
Expand All @@ -21,7 +22,16 @@ export function configureForSwc(tree: Tree, projectRoot: string) {
rootPackageJson.devDependencies?.['@swc/cli'];

if (!tree.exists(swcConfigPath)) {
addSwcConfig(tree, swcConfigPath);
addSwcConfig(tree, projectRoot);
}

if (tree.exists(swcConfigPath)) {
updateJson(tree, swcConfigPath, (json) => {
return {
...json,
exclude: [...json.exclude, '.*.d.ts$'],
};
});
}

if (!hasSwcDepedency || !hasSwcCliDependency) {
Expand Down

0 comments on commit 200710a

Please sign in to comment.