Skip to content

Commit

Permalink
feat(node): update CNW to support generating a node server with a fra…
Browse files Browse the repository at this point in the history
…mework
  • Loading branch information
ndcunningham committed Jan 12, 2023
1 parent ba3fd62 commit 01ad49d
Show file tree
Hide file tree
Showing 20 changed files with 196 additions and 20 deletions.
8 changes: 7 additions & 1 deletion docs/generated/cli/create-nx-workspace.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,12 @@ Default: `main`

Default base to use for new projects

### framework

Type: `string`

Framework option to be used when the node-server preset is selected

### help

Type: `boolean`
Expand Down Expand Up @@ -113,7 +119,7 @@ Package manager to use

Type: `string`

Customizes the initial content of your workspace. Default presets include: ["apps", "empty", "core", "npm", "ts", "web-components", "angular-monorepo", "angular-standalone", "react-monorepo", "react-standalone", "react-native", "expo", "next", "nest", "express", "react", "angular"]. To build your own see https://nx.dev/packages/nx-plugin#preset
Customizes the initial content of your workspace. Default presets include: ["apps", "empty", "core", "npm", "ts", "web-components", "angular-monorepo", "angular-standalone", "react-monorepo", "react-standalone", "react-native", "expo", "next", "nest", "express", "react", "angular", "node-server"]. To build your own see https://nx.dev/packages/nx-plugin#preset

### skipGit

Expand Down
6 changes: 6 additions & 0 deletions docs/generated/packages/node/generators/application.json
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,12 @@
"description": "The port which the server will be run on",
"type": "number",
"default": 3000
},
"rootProject": {
"description": "Create node application at the root of the workspace",
"type": "boolean",
"default": false,
"hidden": true
}
},
"required": [],
Expand Down
8 changes: 7 additions & 1 deletion docs/generated/packages/nx/documents/create-nx-workspace.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,12 @@ Default: `main`

Default base to use for new projects

### framework

Type: `string`

Framework option to be used when the node-server preset is selected

### help

Type: `boolean`
Expand Down Expand Up @@ -113,7 +119,7 @@ Package manager to use

Type: `string`

Customizes the initial content of your workspace. Default presets include: ["apps", "empty", "core", "npm", "ts", "web-components", "angular-monorepo", "angular-standalone", "react-monorepo", "react-standalone", "react-native", "expo", "next", "nest", "express", "react", "angular"]. To build your own see https://nx.dev/packages/nx-plugin#preset
Customizes the initial content of your workspace. Default presets include: ["apps", "empty", "core", "npm", "ts", "web-components", "angular-monorepo", "angular-standalone", "react-monorepo", "react-standalone", "react-native", "expo", "next", "nest", "express", "react", "angular", "node-server"]. To build your own see https://nx.dev/packages/nx-plugin#preset

### skipGit

Expand Down
5 changes: 5 additions & 0 deletions docs/generated/packages/workspace/generators/new.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,11 @@
"description": "The package manager used to install dependencies.",
"type": "string",
"enum": ["npm", "yarn", "pnpm"]
},
"framework": {
"description": "The framework which the application is using",
"type": "string",
"enum": ["express", "koa", "fastify", "connect"]
}
},
"additionalProperties": true,
Expand Down
5 changes: 5 additions & 0 deletions docs/generated/packages/workspace/generators/preset.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@
"description": "The package manager used to install dependencies.",
"type": "string",
"enum": ["npm", "yarn", "pnpm"]
},
"framework": {
"description": "The framework which the application is using",
"type": "string",
"enum": ["express", "koa", "fastify", "connect"]
}
},
"presets": []
Expand Down
63 changes: 61 additions & 2 deletions packages/create-nx-workspace/bin/create-nx-workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ type Arguments = {
appName: string;
cli: string;
style: string;
framework: string;
nxCloud: boolean;
allPrompts: boolean;
packageManager: PackageManager;
Expand Down Expand Up @@ -62,6 +63,7 @@ enum Preset {
Express = 'express',
React = 'react',
Angular = 'angular',
NodeServer = 'node-server',
}

const presetOptions: { name: Preset; message: string }[] = [
Expand Down Expand Up @@ -96,6 +98,10 @@ const presetOptions: { name: Preset; message: string }[] = [
message:
'react-native [a monorepo with a single React Native application]',
},
{
name: Preset.NodeServer,
message: 'node [a standalone repo with a single Node Server]',
},
];

const nxVersion = require('../package.json').version;
Expand Down Expand Up @@ -145,6 +151,10 @@ export const commandsObject: yargs.Argv<Arguments> = yargs
describe: chalk.dim`Style option to be used when a preset with pregenerated app is selected`,
type: 'string',
})
.option('framework', {
describe: chalk.dim`Framework option to be used when the node-server preset is selected`,
type: 'string',
})
.option('nxCloud', {
describe: chalk.dim(messages.getPromptMessage('nxCloudCreation')),
type: 'boolean',
Expand Down Expand Up @@ -224,6 +234,7 @@ async function main(parsedArgs: yargs.Arguments<Arguments>) {
ci,
skipGit,
commit,
framework,
} = parsedArgs;

output.log({
Expand All @@ -248,6 +259,7 @@ async function main(parsedArgs: yargs.Arguments<Arguments>) {
style,
nxCloud,
defaultBase,
framework,
}
);

Expand Down Expand Up @@ -300,7 +312,7 @@ async function getConfiguration(
argv: yargs.Arguments<Arguments>
): Promise<void> {
try {
let name, appName, style, preset;
let name, appName, style, preset, framework;

output.log({
title:
Expand Down Expand Up @@ -343,6 +355,9 @@ async function getConfiguration(
} else {
name = await determineRepoName(argv);
appName = await determineAppName(preset, argv);
if (preset === Preset.NodeServer) {
framework = await determineFramework(preset, argv);
}
}
style = await determineStyle(preset, argv);
}
Expand All @@ -358,6 +373,7 @@ async function getConfiguration(
preset,
appName,
style,
framework,
cli,
nxCloud,
packageManager,
Expand Down Expand Up @@ -643,6 +659,47 @@ async function determineAppName(
});
}

async function determineFramework(
preset: Preset,
parsedArgs: yargs.Arguments<Arguments>
): Promise<string> {
if (preset !== Preset.NodeServer) {
return Promise.resolve('');
}

const frameworkChoices = ['express', 'koa', 'fastify', 'connect'];

if (!parsedArgs.framework) {
return enquirer
.prompt([
{
message: 'What framework should be used?',
type: 'select',
name: 'framework',
choices: frameworkChoices,
},
])
.then((a: { framework: string }) => a.framework);
}

const foundFramework = frameworkChoices.indexOf(parsedArgs.framework);

if (foundFramework < 0) {
output.error({
title: 'Invalid framwork',
bodyLines: [
`It must be one of the following:`,
'',
...frameworkChoices.map((choice) => choice),
],
});

process.exit(1);
}

return Promise.resolve(parsedArgs.framework);
}

function isValidCli(cli: string): cli is 'angular' | 'nx' {
return ['nx', 'angular'].indexOf(cli) !== -1;
}
Expand Down Expand Up @@ -685,7 +742,8 @@ async function determineStyle(
preset === Preset.Nest ||
preset === Preset.Express ||
preset === Preset.ReactNative ||
preset === Preset.Expo
preset === Preset.Expo ||
preset === Preset.NodeServer
) {
return Promise.resolve(null);
}
Expand Down Expand Up @@ -1182,6 +1240,7 @@ function pointToTutorialAndCourse(preset: Preset) {
});
break;
case Preset.Express:
case Preset.NodeServer:
output.addVerticalSeparator();
output.note({
title,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ describe('app', () => {
await applicationGenerator(tree, {
name: 'myNodeApp',
standaloneConfig: false,
bundler: 'webpack',
});
const project = readProjectConfiguration(tree, 'my-node-app');
expect(project.root).toEqual('my-node-app');
Expand Down
45 changes: 32 additions & 13 deletions packages/node/src/generators/application/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import { Linter, lintProjectGenerator } from '@nrwl/linter';
import { jestProjectGenerator } from '@nrwl/jest';
import { runTasksInSerial } from '@nrwl/workspace/src/utilities/run-tasks-in-serial';

import { Schema } from './schema';
import { NodeJsFrameWorks, Schema } from './schema';
import { initGenerator } from '../init/init';
import { getRelativePathToRootTsConfig } from '@nrwl/workspace/src/utilities/typescript';
import {
Expand All @@ -43,6 +43,8 @@ import {
} from '../../utils/versions';
import { prompt } from 'enquirer';

import * as shared from '@nrwl/workspace/src/utils/create-ts-config';

export interface NormalizedSchema extends Schema {
appProjectRoot: string;
parsedTags: string[];
Expand Down Expand Up @@ -290,14 +292,28 @@ function addProjectDependencies(
}

function updateTsConfigOptions(tree: Tree, options: NormalizedSchema) {
// updatae tsconfig.app.json to typecheck default exports https://www.typescriptlang.org/tsconfig#esModuleInterop
updateJson(tree, `${options.appProjectRoot}/tsconfig.app.json`, (json) => ({
...json,
compilerOptions: {
...json.compilerOptions,
esModuleInterop: true,
},
}));
if (options.framework && options?.bundler === 'esbuild') {
// updatae tsconfig.app.json to typecheck default exports https://www.typescriptlang.org/tsconfig#esModuleInterop
updateJson(tree, `${options.appProjectRoot}/tsconfig.app.json`, (json) => ({
...json,
compilerOptions: {
...json.compilerOptions,
esModuleInterop: true,
},
}));
}

if (options.rootProject) {
updateJson(tree, `${options.appProjectRoot}/tsconfig.json`, (json) => ({
compilerOptions: {
...shared.tsConfigBaseOptions,
...json.compilerOptions,
},
...json,
extends: undefined,
exclude: ['node_modules', 'tmp'],
}));
}
}

export async function applicationGenerator(tree: Tree, schema: Schema) {
Expand All @@ -313,9 +329,8 @@ export async function applicationGenerator(tree: Tree, schema: Schema) {
addProjectDependencies(tree, options);
addAppFiles(tree, options);
addProject(tree, options);
if (options.framework && options?.bundler === 'esbuild') {
updateTsConfigOptions(tree, options);
}

updateTsConfigOptions(tree, options);

if (options.linter !== Linter.None) {
const lintTask = await addLintingToApplication(tree, {
Expand Down Expand Up @@ -365,7 +380,11 @@ function normalizeOptions(host: Tree, options: Schema): NormalizedSchema {

const appProjectName = appDirectory.replace(new RegExp('/', 'g'), '-');

const appProjectRoot = joinPathFragments(appsDir, appDirectory);
const appProjectRoot = options.rootProject
? '.'
: joinPathFragments(appsDir, appDirectory);

options.bundler = options.bundler ?? 'esbuild';

const parsedTags = options.tags
? options.tags.split(',').map((s) => s.trim())
Expand Down
1 change: 1 addition & 0 deletions packages/node/src/generators/application/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export interface Schema {
bundler?: 'esbuild' | 'webpack';
framework?: NodeJsFrameWorks;
port?: number;
rootProject?: boolean;
}

export type NodeJsFrameWorks = 'express' | 'koa' | 'fastify' | 'connect';
6 changes: 6 additions & 0 deletions packages/node/src/generators/application/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,12 @@
"description": "The port which the server will be run on",
"type": "number",
"default": 3000
},
"rootProject": {
"description": "Create node application at the root of the workspace",
"type": "boolean",
"default": false,
"hidden": true
}
},
"required": []
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,31 @@ Visit the [Nx Documentation](https://nx.dev) to learn more.
"
`;
exports[`@nrwl/workspace:generateWorkspaceFiles README.md should be created for NodeServer preset 1`] = `
"# Proj
<a href=\\"https://nx.dev\\" target=\\"_blank\\" rel=\\"noreferrer\\"><img src=\\"https://raw.githubusercontent.com/nrwl/nx/master/images/nx-logo.png\\" width=\\"45\\"></a>
**This workspace has been generated by [Nx, a Smart, fast and extensible build system.](https://nx.dev)**
## Development server
Run \`nx serve app1\` for a dev server. Navigate to http://localhost:4200/. The app will automatically reload if you change any of the source files.
## Understand this workspace
Run \`nx graph\` to see a diagram of the dependencies of the projects.
## Remote caching
Run \`npx nx connect-to-nx-cloud\` to enable [remote caching](https://nx.app) and make CI faster.
## Further help
Visit the [Nx Documentation](https://nx.dev) to learn more.
"
`;
exports[`@nrwl/workspace:generateWorkspaceFiles README.md should be created for ReactMonorepo preset 1`] = `
"# Proj
Expand Down
4 changes: 4 additions & 0 deletions packages/workspace/src/generators/new/generate-preset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ export function generatePreset(host: Tree, opts: NormalizedSchema) {
opts.linter ? `--linter=${opts.linter}` : null,
opts.npmScope ? `--npmScope=${opts.npmScope}` : `--npmScope=${opts.name}`,
opts.preset ? `--preset=${opts.preset}` : null,
opts.framework ? `--framework=${opts.framework}` : null,
opts.packageManager ? `--packageManager=${opts.packageManager}` : null,
parsedArgs.interactive ? '--interactive=true' : '--interactive=false',
].filter((e) => !!e);
Expand Down Expand Up @@ -112,6 +113,9 @@ function getPresetDependencies(preset: string, version?: string) {
case Preset.WebComponents:
return { dependencies: {}, dev: { '@nrwl/web': nxVersion } };

case Preset.NodeServer:
return { dependencies: {}, dev: { '@nrwl/node': nxVersion } };

default: {
return {
dev: {},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ describe('@nrwl/workspace:generateWorkspaceFiles', () => {
Preset.NextJs,
Preset.WebComponents,
Preset.Express,
Preset.NodeServer,
].includes(Preset[preset])
) {
appName = 'app1';
Expand Down
Loading

0 comments on commit 01ad49d

Please sign in to comment.