Создание пустого Angular проекта и связь его с существующим сервером на NestJS
Создание приложения происходит через nx схематик для Angular.
Адрес сервера задается жестко в коде, в следую щих постах адрес будет перенесен в переменные окружения.
Для запуска E2E-тестов используется "Playwright".
1. Устанавливаем необходимые библиотеки и создаем пустое Angular приложение
Команды
# Install all need main dev-dependencies
npm install --save-dev @nx/angular@19.5.3
# Create Angular application
./node_modules/.bin/nx g @nx/angular:application --directory=apps/client --name=client --projectNameAndRootFormat=as-provided --style=scss --ssr=true --viewEncapsulation=None --addTailwind=true --e2eTestRunner=playwright --bundler=webpack
Вывод консоли
$ npm install --save-dev @nx/angular@19.5.3
added 222 packages, removed 278 packages, changed 3 packages, and audited 2136 packages in 39s
292 packages are looking for funding
run `npm fund` for details
14 vulnerabilities (4 moderate, 10 high)
To address issues that do not require attention, run:
npm audit fix
To address all issues (including breaking changes), run:
npm audit fix --force
Run `npm audit` for details.
$ ./node_modules/.bin/nx g @nx/angular:application --directory=apps/client --name=client --projectNameAndRootFormat=as-provided --style=scss --ssr=true --viewEncapsulation=None --addTailwind=true --e2eTestRunner=playwright --bundler=webpack
NX Generating @nx/angular:application
Fetching @nx/playwright...
UPDATE .gitignore
UPDATE .prettierignore
UPDATE package.json
UPDATE nx.json
CREATE apps/client/project.json
CREATE apps/client/src/index.html
CREATE apps/client/src/styles.scss
CREATE apps/client/tsconfig.app.json
CREATE apps/client/tsconfig.editor.json
CREATE apps/client/tsconfig.json
CREATE apps/client/public/favicon.ico
CREATE apps/client/src/app/app.component.scss
CREATE apps/client/src/app/app.component.html
CREATE apps/client/src/app/app.component.spec.ts
CREATE apps/client/src/app/app.component.ts
CREATE apps/client/src/app/app.config.ts
CREATE apps/client/src/app/app.routes.ts
CREATE apps/client/src/app/nx-welcome.component.ts
CREATE apps/client/src/main.ts
CREATE apps/client/tailwind.config.js
CREATE apps/client/.eslintrc.json
CREATE apps/client/jest.config.ts
CREATE apps/client/src/test-setup.ts
CREATE apps/client/tsconfig.spec.json
CREATE apps/client-e2e/project.json
CREATE apps/client-e2e/src/example.spec.ts
CREATE apps/client-e2e/playwright.config.ts
CREATE apps/client-e2e/tsconfig.json
CREATE apps/client-e2e/.eslintrc.json
UPDATE .vscode/extensions.json
CREATE apps/client/src/main.server.ts
CREATE apps/client/src/app/app.config.server.ts
CREATE apps/client/tsconfig.server.json
CREATE apps/client/server.ts
npm WARN deprecated abab@2.0.6: Use your platform's native atob() and btoa() methods instead
npm WARN deprecated domexception@4.0.0: Use your platform's native DOMException instead
added 364 packages, removed 57 packages, changed 10 packages, and audited 2443 packages in 24s
297 packages are looking for funding
run `npm fund` for details
12 vulnerabilities (2 moderate, 10 high)
To address issues that do not require attention, run:
npm audit fix
To address all issues (including breaking changes), run:
npm audit fix --force
Run `npm audit` for details.
NX 👀 View Details of client
Run "nx show project client" to view details about this project.
2. Запускаем сборку всех проектов
Команды
# Build all applications and library
npm run build
Вывод консоли
$ npm run build
> @nestjs-mod-fullstack/source@0.0.0 build
> npm run generate && npm run tsc:lint && ./node_modules/.bin/nx run-many --exclude=@nestjs-mod-fullstack/source --all -t=build --skip-nx-cache=true
> @nestjs-mod-fullstack/source@0.0.0 generate
> ./node_modules/.bin/nx run-many --exclude=@nestjs-mod-fullstack/source --all -t=generate --skip-nx-cache=true && npm run make-ts-list && npm run lint:fix
NX Successfully ran target generate for 0 projects (37ms)
> @nestjs-mod-fullstack/source@0.0.0 make-ts-list
> ./node_modules/.bin/rucken make-ts-list
> @nestjs-mod-fullstack/source@0.0.0 lint:fix
> npm run tsc:lint && ./node_modules/.bin/nx run-many --exclude=@nestjs-mod-fullstack/source --all -t=lint --fix
> @nestjs-mod-fullstack/source@0.0.0 tsc:lint
> ./node_modules/.bin/tsc --noEmit -p tsconfig.base.json
apps/client/src/test-setup.ts:1:1 - error TS2578: Unused '@ts-expect-error' directive.
1 // @ts-expect-error https://thymikee.github.io/jest-preset-angular/docs/getting-started/test-environment
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Found 1 error in apps/client/src/test-setup.ts:1
3. Получаем ошибку "Unused '@ts-expect-error' directive." и решаем ее
Так как nx содержит множество различных шаблонов под разные фреймворки, часто можно встретить неявные ошибки которые не понятно как устранять, для обхода текущей ошибки просто перебьем типизацию и удалим директиву.
Обновленный файл apps/client/src/test-setup.ts
(globalThis as any).ngJest = {
testEnvironmentOptions: {
errorOnUnknownElements: true,
errorOnUnknownProperties: true,
},
};
import 'jest-preset-angular/setup-jest';
4. Повторно запускаем сборку всех проектов
Команды
# Build all applications and library
npm run build
Вывод консоли
$ npm run build
> @nestjs-mod-fullstack/source@0.0.0 build
> npm run generate && npm run tsc:lint && ./node_modules/.bin/nx run-many --exclude=@nestjs-mod-fullstack/source --all -t=build --skip-nx-cache=true
> @nestjs-mod-fullstack/source@0.0.0 generate
> ./node_modules/.bin/nx run-many --exclude=@nestjs-mod-fullstack/source --all -t=generate --skip-nx-cache=true && npm run make-ts-list && npm run lint:fix
NX Successfully ran target generate for 0 projects (25ms)
> @nestjs-mod-fullstack/source@0.0.0 make-ts-list
> ./node_modules/.bin/rucken make-ts-list
> @nestjs-mod-fullstack/source@0.0.0 lint:fix
> npm run tsc:lint && ./node_modules/.bin/nx run-many --exclude=@nestjs-mod-fullstack/source --all -t=lint --fix
> @nestjs-mod-fullstack/source@0.0.0 tsc:lint
> ./node_modules/.bin/tsc --noEmit -p tsconfig.base.json
✔ nx run server:lint [existing outputs match the cache, left as is]
✔ nx run server-e2e:lint [existing outputs match the cache, left as is]
✔ nx run client:lint (1s)
—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
NX Successfully ran target lint for 3 projects (1s)
With additional flags:
--fix=true
Nx read the output from the cache instead of running the command for 2 out of 3 tasks.
> @nestjs-mod-fullstack/source@0.0.0 tsc:lint
> ./node_modules/.bin/tsc --noEmit -p tsconfig.base.json
✔ nx run server:build:production (3s)
✔ nx run client:build:production (15s)
————————————————————————————————————————————— ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
NX Successfully ran target build for 2 projects (15s)
5. Добавляем команду в конфигурацию pm2 для запуска Angular приложения в режиме watch
Обновленная конфигурация pm2 ecosystem.config.json
{
"apps": [
{
"name": "server",
"script": "node ./dist/apps/server/main.js",
"node_args": "-r dotenv/config"
},
{
"name": "client",
"script": "./node_modules/.bin/nx serve client --host=0.0.0.0 --disable-host-check",
"node_args": "-r dotenv/config"
}
]
}