diff --git a/docs/src/content/docs/en/blog/migrating-from-aws-pdk.mdx b/docs/src/content/docs/en/blog/migrating-from-aws-pdk.mdx index 16ea1650b..05a34ab38 100644 --- a/docs/src/content/docs/en/blog/migrating-from-aws-pdk.mdx +++ b/docs/src/content/docs/en/blog/migrating-from-aws-pdk.mdx @@ -5,7 +5,7 @@ date: 2025-09-26 authors: - jack --- -import { Steps, Tabs, TabItem } from '@astrojs/starlight/components'; +import { Steps } from '@astrojs/starlight/components'; import Snippet from '@components/snippet.astro'; import CreateNxWorkspaceCommand from '@components/create-nx-workspace-command.astro'; import RunGenerator from '@components/run-generator.astro'; @@ -36,7 +36,7 @@ Note also that some features of PDK don't have exact equivalents. Refer to the [ ::: :::caution[Point-in-Time Guide] -This is written as a point-of-time guide and will most likely not be updated as the Nx Plugin for AWS evolves. To compensate for this, the guide pins the version of `@aws/nx-plugin` to `0.50.0`. You can try with the latest version if following along, but there may be some deviations from the guide. +This is written as a point-of-time guide and will most likely not be updated as the Nx Plugin for AWS evolves. To compensate for this, the guide pins the version of `@aws/nx-plugin` to `1.0.0-rc.33`. You can try with the latest version if following along, but there may be some deviations from the guide. ::: ## Example Migration: Shopping List Application @@ -54,28 +54,7 @@ The shopping list application consists of the following PDK project types: To start, we'll create a new workspace for our new project. While more extreme than an in-place migration, this approach gives us the cleanest end result. Creating an Nx workspace is equivalent to using PDK's `MonorepoTsProject`: - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=pnpm --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=yarn --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=npm --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=bun --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - + Open up the `shopping-list` directory this command creates in your favourite IDE. diff --git a/docs/src/content/docs/en/snippets/pdk-migration/example/01-migrate-api.mdx b/docs/src/content/docs/en/snippets/pdk-migration/example/01-migrate-api.mdx index 45defc15d..83bbef181 100644 --- a/docs/src/content/docs/en/snippets/pdk-migration/example/01-migrate-api.mdx +++ b/docs/src/content/docs/en/snippets/pdk-migration/example/01-migrate-api.mdx @@ -23,9 +23,9 @@ If you used OpenAPI or TypeSpec as your modelling language, or have handlers imp #### Generate a TypeScript Smithy API -Run the `ts#smithy-api` generator to set up your api project in `packages/api`: +Run the `ts#api` generator with `framework` set to `smithy` to set up your api project in `packages/api`: - + You will notice this generates a `model` project, as well as a `backend` project. The `model` project contains your Smithy model, and `backend` contains your server implementation. @@ -134,6 +134,8 @@ The shopping list application's lambda handlers rely on the `@aws-sdk/client-dyn Then, let's copy the `handlers/src/dynamo-client.ts` file from the PDK project to `backend/src/operations` so it's available for our handlers. +The `ts#smithy-api` generator scaffolds an example `Echo` operation. Since we removed this from our model, delete the corresponding handler in `backend/src/operations/echo.ts`. We'll register our migrated operations in `service.ts` further below. + To migrate the handlers, you can follow these general steps: @@ -583,7 +585,7 @@ Additionally, update `packages/api/backend/project.json` and update `metadata.ap "generator": "ts#smithy-api", - "apiName": "api", + "apiName": "my-api", - "auth": "IAM", + "auth": "iam", "modelProject": "@shopping-list/api-model", "ports": [3001] }, diff --git a/docs/src/content/docs/en/snippets/pdk-migration/example/02-migrate-website.mdx b/docs/src/content/docs/en/snippets/pdk-migration/example/02-migrate-website.mdx index 96036f265..acf887348 100644 --- a/docs/src/content/docs/en/snippets/pdk-migration/example/02-migrate-website.mdx +++ b/docs/src/content/docs/en/snippets/pdk-migration/example/02-migrate-website.mdx @@ -11,21 +11,21 @@ import InstallCommand from '@components/install-command.astro'; The `CloudscapeReactTsWebsiteProject` used in the shopping list application configured a React website with CloudScape and Cognito authentication built in. -This project type leveraged [`create-react-app`](https://github.com/facebook/create-react-app), which is now deprecated. For migrating the website in this guide, we will use the `ts#react-website` generator, which uses more modern and supported technologies, namely [Vite](https://vite.dev/). +This project type leveraged [`create-react-app`](https://github.com/facebook/create-react-app), which is now deprecated. For migrating the website in this guide, we will use the `ts#website` generator, which uses more modern and supported technologies, namely [Vite](https://vite.dev/). As part of the migration, we will also move from PDK's configured React Router to [TanStack Router](https://tanstack.com/router), which adds additional type-safety to website routing. #### Generate a React Website -Run the `ts#react-website` generator to set up your website project in `packages/website`: +Run the `ts#website` generator with `framework` set to `react` to set up your website project in `packages/website`. Since the shopping list application is built with CloudScape components, we also set `ux` to `cloudscape` (the default is `shadcn`): - + #### Add Cognito Authentication -The React website generator above doesn't bundle cognito authentication by default like `CloudscapeReactTsWebsiteProject`, instead it's added explicitly via the `ts#react-website#auth` generator. +The React website generator above doesn't bundle cognito authentication by default like `CloudscapeReactTsWebsiteProject`, instead it's added explicitly via the `ts#website#auth` generator. - + This adds React components which manage the appropriate redirects to ensure users log in using the Cognito hosted UI. This also adds a CDK construct to deploy the Cognito resources in `packages/common/constructs`, called `UserIdentity`. @@ -61,6 +61,23 @@ The `CloudscapeReactTsWebsiteProject` automatically included a dependency on `@a +`@aws-northstar/ui` bundles a code editor component which depends on `ace-builds`, using a webpack-specific import that Vite cannot resolve. Since our shopping list application doesn't use this component, we exclude it from the bundle by adding it to the `external` configuration within the existing `build` options in `packages/website/vite.config.mts`: + +```diff lang="ts" +// packages/website/vite.config.mts + build: { + outDir: '../../dist/packages/website/bundle', + emptyOutDir: true, + reportCompressedSize: true, + commonjsOptions: { + transformMixedEsModules: true, + }, ++ rollupOptions: { ++ external: ['ace-builds/webpack-resolver'], ++ }, + }, +``` + #### Move the Components and Pages The [shopping list application](https://aws.github.io/aws-pdk/getting_started/shopping_list_app.html#create-new-pages-components) has one component called `CreateItem`, and two pages, `ShoppingList` and `ShoppingLists`. We'll migrate these to the new website, making a few adjustments since we're using TanStack Router and the Nx Plugin for AWS TypeScript client code generator. @@ -79,12 +96,14 @@ Note that you'll now have some build errors visible in your IDE, we'll need to m #### Migrate from React Router to TanStack Router -Since we're using [file-based routing](https://tanstack.com/router/latest/docs/framework/react/routing/file-based-routing), we can use the website local development server to manage automatically generating route configuration. Let's start the local website server: +Since we're using [file-based routing](https://tanstack.com/router/latest/docs/framework/react/routing/file-based-routing), we can use the website local development server to manage automatically generating route configuration. + +Let's start the local website server: - + :::tip -We're using the `serve-local` target here, which also starts local servers for any APIs which have been connected with `connection`, and hot-reloads if your website, model, or backend changes! This allows us to test our API and website locally before we've even written any CDK code. +We're using the `dev` target here, which also starts local servers for any APIs which have been connected with `connection`, and hot-reloads if your website, model, or backend changes! This allows us to test our API and website locally before we've even written any CDK code. ::: You'll see some errors, but the local website server should start on port `4200`, as well as the local Smithy API server on port `3001`. diff --git a/docs/src/content/docs/en/snippets/pdk-migration/faq/type-safe-api.mdx b/docs/src/content/docs/en/snippets/pdk-migration/faq/type-safe-api.mdx index edf0025e8..a417e24ee 100644 --- a/docs/src/content/docs/en/snippets/pdk-migration/faq/type-safe-api.mdx +++ b/docs/src/content/docs/en/snippets/pdk-migration/faq/type-safe-api.mdx @@ -26,7 +26,7 @@ For Python, the [python-fastapi](https://openapi-generator.tech/docs/generators/ ##### Client -For TypeScript clients, you can use the `ts#react-website` generator and `connection` generator with an example `ts#smithy-api` to see how clients are generated and integrated with a website. This configures build targets which generate clients by invoking our `open-api#ts-client` or `open-api#ts-hooks` generators. You can use these generators yourself by pointing them at your OpenAPI Specification. +For TypeScript clients, you can use the `ts#website` generator and `connection` generator with an example `ts#api` (with `framework` set to `smithy`) to see how clients are generated and integrated with a website. This configures build targets which generate clients by invoking our `open-api#ts-client` or `open-api#ts-hooks` generators. You can use these generators yourself by pointing them at your OpenAPI Specification. For other languages, you can also see if any of the generators from [OpenAPI Generator](https://openapi-generator.tech/docs/generators#client-generators) fit your needs. diff --git a/docs/src/content/docs/es/blog/migrating-from-aws-pdk.mdx b/docs/src/content/docs/es/blog/migrating-from-aws-pdk.mdx index 27e2b4dd8..6a4fb19d6 100644 --- a/docs/src/content/docs/es/blog/migrating-from-aws-pdk.mdx +++ b/docs/src/content/docs/es/blog/migrating-from-aws-pdk.mdx @@ -5,8 +5,7 @@ date: 2025-09-26 authors: - jack --- - -import { Steps, Tabs, TabItem } from '@astrojs/starlight/components'; +import { Steps } from '@astrojs/starlight/components'; import Snippet from '@components/snippet.astro'; import CreateNxWorkspaceCommand from '@components/create-nx-workspace-command.astro'; import RunGenerator from '@components/run-generator.astro'; @@ -37,7 +36,7 @@ Ten en cuenta también que algunas características de PDK no tienen equivalente ::: :::caution[Guía de un momento específico] -Esta guía está escrita para un momento específico y probablemente no se actualizará conforme evolucione el Nx Plugin para AWS. Para compensar esto, la guía fija la versión de `@aws/nx-plugin` a `0.50.0`. Puedes intentar con la última versión si sigues los pasos, pero puede haber desviaciones respecto a la guía. +Esta guía está escrita para un momento específico y probablemente no se actualizará conforme evolucione el Nx Plugin para AWS. Para compensar esto, la guía fija la versión de `@aws/nx-plugin` a `1.0.0-rc.33`. Puedes intentar con la última versión si sigues los pasos, pero puede haber desviaciones respecto a la guía. ::: ## Ejemplo de Migración: Aplicación de Lista de Compras @@ -55,28 +54,7 @@ La aplicación de lista de compras consiste en los siguientes tipos de proyecto Para comenzar, crearemos un nuevo espacio de trabajo para nuestro proyecto nuevo. Aunque más extremo que una migración in situ, este enfoque nos da el resultado final más limpio. Crear un espacio de trabajo Nx es equivalente a usar el `MonorepoTsProject` de PDK: - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=pnpm --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=yarn --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=npm --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=bun --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - + Abre el directorio `shopping-list` que crea este comando en tu IDE favorito. diff --git a/docs/src/content/docs/es/snippets/pdk-migration/example/01-migrate-api.mdx b/docs/src/content/docs/es/snippets/pdk-migration/example/01-migrate-api.mdx index 1c11fdcda..334899b00 100644 --- a/docs/src/content/docs/es/snippets/pdk-migration/example/01-migrate-api.mdx +++ b/docs/src/content/docs/es/snippets/pdk-migration/example/01-migrate-api.mdx @@ -26,7 +26,7 @@ Si usaste OpenAPI o TypeSpec como lenguaje de modelado, o tienes manejadores imp Ejecuta el generador `ts#smithy-api` para configurar tu proyecto de API en `packages/api`: - + Notarás que esto genera un proyecto `model`, así como un proyecto `backend`. El proyecto `model` contiene tu modelo Smithy, y `backend` contiene la implementación del servidor. diff --git a/docs/src/content/docs/es/snippets/pdk-migration/example/02-migrate-website.mdx b/docs/src/content/docs/es/snippets/pdk-migration/example/02-migrate-website.mdx index ac3ced518..b88e48919 100644 --- a/docs/src/content/docs/es/snippets/pdk-migration/example/02-migrate-website.mdx +++ b/docs/src/content/docs/es/snippets/pdk-migration/example/02-migrate-website.mdx @@ -12,21 +12,21 @@ import InstallCommand from '@components/install-command.astro'; El `CloudscapeReactTsWebsiteProject` utilizado en la aplicación de lista de compras configuró un sitio web React con CloudScape y autenticación Cognito integrada. -Este tipo de proyecto utilizaba [`create-react-app`](https://github.com/facebook/create-react-app), que ahora está obsoleto. Para migrar el sitio web en esta guía, usaremos el generador `ts#react-website`, que emplea tecnologías más modernas y soportadas, específicamente [Vite](https://vite.dev/). +Este tipo de proyecto utilizaba [`create-react-app`](https://github.com/facebook/create-react-app), que ahora está obsoleto. Para migrar el sitio web en esta guía, usaremos el generador `ts#website`, que emplea tecnologías más modernas y soportadas, específicamente [Vite](https://vite.dev/). Como parte de la migración, también cambiaremos del React Router configurado por PDK a [TanStack Router](https://tanstack.com/router), que añade mayor seguridad de tipos al enrutamiento del sitio web. #### Generar un sitio web React -Ejecuta el generador `ts#react-website` para configurar tu proyecto de sitio web en `packages/website`: +Ejecuta el generador `ts#website` con `framework` establecido en `react` para configurar tu proyecto de sitio web en `packages/website`: - + #### Añadir autenticación Cognito -El generador de sitios web React anterior no incluye autenticación Cognito por defecto como `CloudscapeReactTsWebsiteProject`, en su lugar se añade explícitamente mediante el generador `ts#react-website#auth`. +El generador de sitios web React anterior no incluye autenticación Cognito por defecto como `CloudscapeReactTsWebsiteProject`, en su lugar se añade explícitamente mediante el generador `ts#website#auth`. - + Esto añade componentes React que gestionan las redirecciones necesarias para asegurar que los usuarios inicien sesión usando la interfaz alojada de Cognito. También añade un constructo CDK para desplegar los recursos de Cognito en `packages/common/constructs`, llamado `UserIdentity`. @@ -62,6 +62,23 @@ El `CloudscapeReactTsWebsiteProject` incluía automáticamente una dependencia d +`@aws-northstar/ui` incluye un componente de editor de código que depende de `ace-builds`, usando una importación específica de webpack que Vite no puede resolver. Como nuestra aplicación de lista de compras no usa este componente, lo excluimos del bundle añadiéndolo a la configuración `external` dentro de las opciones `build` existentes en `packages/website/vite.config.mts`: + +```diff lang="ts" +// packages/website/vite.config.mts + build: { + outDir: '../../dist/packages/website/bundle', + emptyOutDir: true, + reportCompressedSize: true, + commonjsOptions: { + transformMixedEsModules: true, + }, ++ rollupOptions: { ++ external: ['ace-builds/webpack-resolver'], ++ }, + }, +``` + #### Mover componentes y páginas La [aplicación de lista de compras](https://aws.github.io/aws-pdk/getting_started/shopping_list_app.html#create-new-pages-components) tiene un componente llamado `CreateItem`, y dos páginas, `ShoppingList` y `ShoppingLists`. Migraremos estos elementos al nuevo sitio web, haciendo ajustes por el uso de TanStack Router y el generador de código cliente TypeScript del Plugin Nx para AWS. @@ -80,12 +97,14 @@ Notarás algunos errores de compilación en tu IDE, necesitaremos hacer algunos #### Migrar de React Router a TanStack Router -Al usar [enrutamiento basado en archivos](https://tanstack.com/router/latest/docs/framework/react/routing/file-based-routing), podemos usar el servidor de desarrollo local para generar automáticamente la configuración de rutas. Iniciemos el servidor local: +Al usar [enrutamiento basado en archivos](https://tanstack.com/router/latest/docs/framework/react/routing/file-based-routing), podemos usar el servidor de desarrollo local del sitio web para gestionar la generación automática de la configuración de rutas. + +Iniciemos el servidor local del sitio web: - + :::tip -Usamos el objetivo `serve-local` que también inicia servidores locales para APIs conectadas con `connection`, y recarga en caliente si cambian el sitio web, modelo o backend. ¡Esto nos permite probar la API y el sitio web localmente antes de escribir código CDK! +Usamos el objetivo `dev` aquí, que también inicia servidores locales para APIs conectadas con `connection`, y recarga en caliente si cambian el sitio web, modelo o backend. ¡Esto nos permite probar la API y el sitio web localmente antes de escribir código CDK! ::: Verás algunos errores, pero el servidor local debería iniciarse en el puerto `4200`, junto con el servidor Smithy local en el puerto `3001`. diff --git a/docs/src/content/docs/fr/blog/migrating-from-aws-pdk.mdx b/docs/src/content/docs/fr/blog/migrating-from-aws-pdk.mdx index 3ff6afced..c40c27f0f 100644 --- a/docs/src/content/docs/fr/blog/migrating-from-aws-pdk.mdx +++ b/docs/src/content/docs/fr/blog/migrating-from-aws-pdk.mdx @@ -6,7 +6,7 @@ authors: - jack --- -import { Steps, Tabs, TabItem } from '@astrojs/starlight/components'; +import { Steps } from '@astrojs/starlight/components'; import Snippet from '@components/snippet.astro'; import CreateNxWorkspaceCommand from '@components/create-nx-workspace-command.astro'; import RunGenerator from '@components/run-generator.astro'; @@ -37,7 +37,7 @@ Notez aussi que certaines fonctionnalités de PDK n'ont pas d'équivalents exact ::: :::caution[Guide à un instant donné] -Ce guide représente un instantané et ne sera probablement pas mis à jour avec l'évolution du Nx Plugin pour AWS. Pour compenser, le guide utilise la version `0.50.0` de `@aws/nx-plugin`. Vous pouvez essayer avec la dernière version, mais il pourrait y avoir des écarts par rapport au guide. +Ce guide représente un instantané et ne sera probablement pas mis à jour avec l'évolution du Nx Plugin pour AWS. Pour compenser, le guide utilise la version `1.0.0-rc.33` de `@aws/nx-plugin`. Vous pouvez essayer avec la dernière version, mais il pourrait y avoir des écarts par rapport au guide. ::: ## Exemple de migration : Application de liste de courses @@ -55,28 +55,7 @@ L'application de liste de courses contient les types de projets PDK suivants : Pour commencer, nous allons créer un nouvel espace de travail pour notre projet. Bien que plus radical qu'une migration in situ, cette approche donne le résultat le plus propre. Créer un espace Nx équivaut à utiliser le `MonorepoTsProject` de PDK : - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=pnpm --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=yarn --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=npm --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=bun --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - + Ouvrez le répertoire `shopping-list` créé par cette commande dans votre IDE préféré. diff --git a/docs/src/content/docs/fr/snippets/pdk-migration/example/01-migrate-api.mdx b/docs/src/content/docs/fr/snippets/pdk-migration/example/01-migrate-api.mdx index 29a1da0e9..c3bf1dd05 100644 --- a/docs/src/content/docs/fr/snippets/pdk-migration/example/01-migrate-api.mdx +++ b/docs/src/content/docs/fr/snippets/pdk-migration/example/01-migrate-api.mdx @@ -26,7 +26,7 @@ Si vous avez utilisé OpenAPI ou TypeSpec comme langage de modélisation, ou des Exécutez le générateur `ts#smithy-api` pour configurer votre projet d'API dans `packages/api` : - + Vous remarquerez que cela génère un projet `model` ainsi qu'un projet `backend`. Le projet `model` contient votre modèle Smithy, et `backend` contient l'implémentation serveur. diff --git a/docs/src/content/docs/fr/snippets/pdk-migration/example/02-migrate-website.mdx b/docs/src/content/docs/fr/snippets/pdk-migration/example/02-migrate-website.mdx index 8414d4684..2a3a0a217 100644 --- a/docs/src/content/docs/fr/snippets/pdk-migration/example/02-migrate-website.mdx +++ b/docs/src/content/docs/fr/snippets/pdk-migration/example/02-migrate-website.mdx @@ -12,21 +12,21 @@ import InstallCommand from '@components/install-command.astro'; Le `CloudscapeReactTsWebsiteProject` utilisé dans l'application de liste de courses configurait un site React avec CloudScape et l'authentification Cognito intégrée. -Ce type de projet s'appuyait sur [`create-react-app`](https://github.com/facebook/create-react-app), qui est maintenant obsolète. Pour migrer le site dans ce guide, nous utiliserons le générateur `ts#react-website`, qui utilise des technologies plus modernes et maintenues, notamment [Vite](https://vite.dev/). +Ce type de projet s'appuyait sur [`create-react-app`](https://github.com/facebook/create-react-app), qui est maintenant obsolète. Pour migrer le site dans ce guide, nous utiliserons le générateur `ts#website`, qui utilise des technologies plus modernes et maintenues, notamment [Vite](https://vite.dev/). Dans le cadre de la migration, nous passerons également du React Router configuré par PDK à [TanStack Router](https://tanstack.com/router), qui ajoute une sécurité typée supplémentaire pour le routage des sites. #### Générer un site React -Exécutez le générateur `ts#react-website` pour configurer votre projet de site dans `packages/website` : +Exécutez le générateur `ts#website` avec `framework` défini sur `react` pour configurer votre projet de site dans `packages/website`. Comme l'application de liste de courses est construite avec des composants CloudScape, nous définissons également `ux` sur `cloudscape` (la valeur par défaut est `shadcn`) : - + #### Ajouter l'authentification Cognito -Le générateur de site React ci-dessus n'inclut pas par défaut l'authentification Cognito comme `CloudscapeReactTsWebsiteProject`, elle est ajoutée explicitement via le générateur `ts#react-website#auth`. +Le générateur de site React ci-dessus n'inclut pas par défaut l'authentification Cognito comme `CloudscapeReactTsWebsiteProject`, elle est ajoutée explicitement via le générateur `ts#website#auth`. - + Ceci ajoute des composants React qui gèrent les redirections appropriées pour garantir que les utilisateurs se connectent via l'interface hébergée de Cognito. Cela ajoute également un construct CDK pour déployer les ressources Cognito dans `packages/common/constructs`, appelé `UserIdentity`. @@ -62,6 +62,23 @@ Le `CloudscapeReactTsWebsiteProject` incluait automatiquement une dépendance su +`@aws-northstar/ui` intègre un composant d'éditeur de code qui dépend de `ace-builds`, utilisant une importation spécifique à webpack que Vite ne peut pas résoudre. Comme notre application de liste de courses n'utilise pas ce composant, nous l'excluons du bundle en l'ajoutant à la configuration `external` dans les options `build` existantes de `packages/website/vite.config.mts` : + +```diff lang="ts" +// packages/website/vite.config.mts + build: { + outDir: '../../dist/packages/website/bundle', + emptyOutDir: true, + reportCompressedSize: true, + commonjsOptions: { + transformMixedEsModules: true, + }, ++ rollupOptions: { ++ external: ['ace-builds/webpack-resolver'], ++ }, + }, +``` + #### Déplacer les composants et pages L'[application de liste de courses](https://aws.github.io/aws-pdk/getting_started/shopping_list_app.html#create-new-pages-components) a un composant appelé `CreateItem`, et deux pages, `ShoppingList` et `ShoppingLists`. Migrons-les vers le nouveau site en ajustant quelques éléments pour utiliser TanStack Router et le générateur de client TypeScript du Plugin Nx pour AWS. @@ -80,12 +97,14 @@ Vous aurez maintenant des erreurs de build dans votre IDE, nous devrons apporter #### Migrer de React Router vers TanStack Router -Comme nous utilisons le [routage basé sur les fichiers](https://tanstack.com/router/latest/docs/framework/react/routing/file-based-routing), nous pouvons utiliser le serveur de développement local pour générer automatiquement la configuration des routes. Démarrons le serveur local : +Comme nous utilisons le [routage basé sur les fichiers](https://tanstack.com/router/latest/docs/framework/react/routing/file-based-routing), nous pouvons utiliser le serveur de développement local pour générer automatiquement la configuration des routes. + +Démarrons le serveur local du site : - + :::tip -Nous utilisons la cible `serve-local` ici, qui démarre aussi les serveurs locaux pour les APIs connectées via `connection`, avec rechargement à chaud si le site, le modèle ou le backend changent ! Cela nous permet de tester notre API et notre site localement avant même d'écrire du code CDK. +Nous utilisons la cible `dev` ici, qui démarre aussi les serveurs locaux pour les APIs connectées via `connection`, avec rechargement à chaud si le site, le modèle ou le backend changent ! Cela nous permet de tester notre API et notre site localement avant même d'écrire du code CDK. ::: Des erreurs peuvent apparaître, mais le serveur local devrait démarrer sur le port `4200`, ainsi que le serveur Smithy local sur le port `3001`. diff --git a/docs/src/content/docs/it/blog/migrating-from-aws-pdk.mdx b/docs/src/content/docs/it/blog/migrating-from-aws-pdk.mdx index ec17610d4..b750784d6 100644 --- a/docs/src/content/docs/it/blog/migrating-from-aws-pdk.mdx +++ b/docs/src/content/docs/it/blog/migrating-from-aws-pdk.mdx @@ -6,7 +6,7 @@ authors: - jack --- -import { Steps, Tabs, TabItem } from '@astrojs/starlight/components'; +import { Steps } from '@astrojs/starlight/components'; import Snippet from '@components/snippet.astro'; import CreateNxWorkspaceCommand from '@components/create-nx-workspace-command.astro'; import RunGenerator from '@components/run-generator.astro'; @@ -37,7 +37,7 @@ Nota inoltre che alcune funzionalità di PDK non hanno equivalenti esatti. Fai r ::: :::caution[Guida ad un momento specifico] -Questa guida è scritta come riferimento temporale e molto probabilmente non verrà aggiornata con l'evoluzione del Plugin Nx per AWS. Per compensare, la guida fissa la versione di `@aws/nx-plugin` a `0.50.0`. Puoi provare con l'ultima versione se segui la guida, ma potrebbero esserci alcune differenze. +Questa guida è scritta come riferimento temporale e molto probabilmente non verrà aggiornata con l'evoluzione del Plugin Nx per AWS. Per compensare, la guida fissa la versione di `@aws/nx-plugin` a `1.0.0-rc.33`. Puoi provare con l'ultima versione se segui la guida, ma potrebbero esserci alcune differenze. ::: ## Migrazione di esempio: Applicazione Lista della Spesa @@ -55,28 +55,7 @@ L'applicazione lista della spesa consiste nei seguenti tipi di progetto PDK: Per iniziare, creeremo un nuovo workspace per il nostro nuovo progetto. Sebbene più drastico di una migrazione in-place, questo approccio garantisce il risultato finale più pulito. Creare un workspace Nx è equivalente all'uso di `MonorepoTsProject` di PDK: - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=pnpm --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=yarn --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=npm --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=bun --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - + Apri la directory `shopping-list` creata da questo comando nel tuo IDE preferito. diff --git a/docs/src/content/docs/it/snippets/pdk-migration/example/01-migrate-api.mdx b/docs/src/content/docs/it/snippets/pdk-migration/example/01-migrate-api.mdx index 465b6aee3..132c18501 100644 --- a/docs/src/content/docs/it/snippets/pdk-migration/example/01-migrate-api.mdx +++ b/docs/src/content/docs/it/snippets/pdk-migration/example/01-migrate-api.mdx @@ -26,7 +26,7 @@ Se hai utilizzato OpenAPI o TypeSpec come linguaggio di modellazione, o hai hand Esegui il generatore `ts#smithy-api` per configurare il tuo progetto API in `packages/api`: - + Noterai che vengono generati un progetto `model` e un progetto `backend`. Il progetto `model` contiene il modello Smithy, mentre `backend` contiene l'implementazione del server. diff --git a/docs/src/content/docs/it/snippets/pdk-migration/example/02-migrate-website.mdx b/docs/src/content/docs/it/snippets/pdk-migration/example/02-migrate-website.mdx index 13d1f5aab..5ed78b897 100644 --- a/docs/src/content/docs/it/snippets/pdk-migration/example/02-migrate-website.mdx +++ b/docs/src/content/docs/it/snippets/pdk-migration/example/02-migrate-website.mdx @@ -20,13 +20,13 @@ Come parte della migrazione, passeremo anche dal React Router configurato da PDK Esegui il generatore `ts#react-website` per configurare il progetto del sito web in `packages/website`: - + #### Aggiungi Autenticazione Cognito Il generatore per siti web React sopra citato non include l'autenticazione Cognito di default come `CloudscapeReactTsWebsiteProject`, ma può essere aggiunta esplicitamente tramite il generatore `ts#react-website#auth`. - + Questo aggiunge componenti React che gestiscono i redirect necessari per garantire il login degli utenti tramite l'UI ospitata da Cognito. Viene inoltre aggiunto un costrutto CDK per distribuire le risorse Cognito in `packages/common/constructs`, chiamato `UserIdentity`. @@ -62,6 +62,23 @@ Il `CloudscapeReactTsWebsiteProject` includeva automaticamente una dipendenza da +`@aws-northstar/ui` include un componente editor di codice che dipende da `ace-builds`, utilizzando un import specifico per webpack che Vite non può risolvere. Poiché la nostra applicazione della lista della spesa non utilizza questo componente, lo escludiamo dal bundle aggiungendolo alla configurazione `external` all'interno delle opzioni `build` esistenti in `packages/website/vite.config.mts`: + +```diff lang="ts" +// packages/website/vite.config.mts + build: { + outDir: '../../dist/packages/website/bundle', + emptyOutDir: true, + reportCompressedSize: true, + commonjsOptions: { + transformMixedEsModules: true, + }, ++ rollupOptions: { ++ external: ['ace-builds/webpack-resolver'], ++ }, + }, +``` + #### Sposta Componenti e Pagine L'[applicazione della lista della spesa](https://aws.github.io/aws-pdk/getting_started/shopping_list_app.html#create-new-pages-components) ha un componente chiamato `CreateItem` e due pagine, `ShoppingList` e `ShoppingLists`. Migreremo questi elementi nel nuovo sito web, apportando alcune modifiche per l'utilizzo di TanStack Router e del generatore di client TypeScript del Plugin Nx per AWS. @@ -80,12 +97,14 @@ Noterai alcuni errori di compilazione nell'IDE: apporteremo ulteriori modifiche #### Migra da React Router a TanStack Router -Utilizzando il [routing basato su file](https://tanstack.com/router/latest/docs/framework/react/routing/file-based-routing), possiamo usare il server di sviluppo locale per generare automaticamente la configurazione delle rotte. Avviamo il server locale del sito web: +Utilizzando il [routing basato su file](https://tanstack.com/router/latest/docs/framework/react/routing/file-based-routing), possiamo usare il server di sviluppo locale per generare automaticamente la configurazione delle rotte. + +Avviamo il server locale del sito web: - + :::tip -Utilizziamo il target `serve-local` che avvia anche server locali per le API connesse tramite `connection`, con hot-reload in caso di modifiche! Questo ci permette di testare API e sito web localmente prima ancora di scrivere codice CDK. +Utilizziamo il target `dev` che avvia anche server locali per le API connesse tramite `connection`, con hot-reload in caso di modifiche al sito web, al modello o al backend! Questo ci permette di testare API e sito web localmente prima ancora di scrivere codice CDK. ::: Potresti vedere alcuni errori, ma il server locale del sito web dovrebbe avviarsi sulla porta `4200`, e il server Smithy API locale sulla porta `3001`. diff --git a/docs/src/content/docs/jp/blog/migrating-from-aws-pdk.mdx b/docs/src/content/docs/jp/blog/migrating-from-aws-pdk.mdx index 37a8c5ea2..fd0c21fe0 100644 --- a/docs/src/content/docs/jp/blog/migrating-from-aws-pdk.mdx +++ b/docs/src/content/docs/jp/blog/migrating-from-aws-pdk.mdx @@ -6,7 +6,7 @@ authors: - jack --- -import { Steps, Tabs, TabItem } from '@astrojs/starlight/components'; +import { Steps } from '@astrojs/starlight/components'; import Snippet from '@components/snippet.astro'; import CreateNxWorkspaceCommand from '@components/create-nx-workspace-command.astro'; import RunGenerator from '@components/run-generator.astro'; @@ -37,7 +37,7 @@ PDKからNx Plugin for AWSへの移行により、以下のメリットが得ら ::: :::caution[特定時点のガイド] -このガイドは特定の時点での内容を記載しており、Nx Plugin for AWSの進化に伴って更新されない可能性があります。これを補うため、ガイド内では`@aws/nx-plugin`のバージョンを`0.50.0`に固定しています。最新版での実行も可能ですが、ガイドとの差異が生じる可能性があります。 +このガイドは特定の時点での内容を記載しており、Nx Plugin for AWSの進化に伴って更新されない可能性があります。これを補うため、ガイド内では`@aws/nx-plugin`のバージョンを`1.0.0-rc.33`に固定しています。最新版での実行も可能ですが、ガイドとの差異が生じる可能性があります。 ::: ## 移行例: ショッピングリストアプリケーション @@ -55,28 +55,7 @@ PDKからNx Plugin for AWSへの移行により、以下のメリットが得ら 最初に、新しいプロジェクト用のワークスペースを作成します。既存環境での移行よりも極端なアプローチですが、最もクリーンな結果を得られます。Nxワークスペースの作成は、PDKの`MonorepoTsProject`に相当します: - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=pnpm --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=yarn --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=npm --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=bun --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - + このコマンドで作成された`shopping-list`ディレクトリを、お気に入りのIDEで開きます。 diff --git a/docs/src/content/docs/jp/snippets/pdk-migration/example/01-migrate-api.mdx b/docs/src/content/docs/jp/snippets/pdk-migration/example/01-migrate-api.mdx index 55314cf63..124ec5355 100644 --- a/docs/src/content/docs/jp/snippets/pdk-migration/example/01-migrate-api.mdx +++ b/docs/src/content/docs/jp/snippets/pdk-migration/example/01-migrate-api.mdx @@ -26,7 +26,7 @@ OpenAPIやTypeSpecをモデリング言語として使用している場合、 `packages/api`にAPIプロジェクトをセットアップするため、`ts#smithy-api`ジェネレーターを実行します: - + これにより`model`プロジェクトと`backend`プロジェクトが生成されます。`model`プロジェクトにはSmithyモデルが含まれ、`backend`にはサーバー実装が含まれます。 diff --git a/docs/src/content/docs/jp/snippets/pdk-migration/example/02-migrate-website.mdx b/docs/src/content/docs/jp/snippets/pdk-migration/example/02-migrate-website.mdx index 75a31509e..333f16403 100644 --- a/docs/src/content/docs/jp/snippets/pdk-migration/example/02-migrate-website.mdx +++ b/docs/src/content/docs/jp/snippets/pdk-migration/example/02-migrate-website.mdx @@ -12,21 +12,21 @@ import InstallCommand from '@components/install-command.astro'; ショッピングリストアプリケーションで使用された `CloudscapeReactTsWebsiteProject` は、CloudScape と Cognito 認証が組み込まれた React ウェブサイトを設定していました。 -このプロジェクトタイプは非推奨となった [`create-react-app`](https://github.com/facebook/create-react-app) を利用していました。このガイドでは、より現代的でサポートされた技術(具体的には [Vite](https://vite.dev/))を使用する `ts#react-website` ジェネレータ を利用してウェブサイトの移行を行います。 +このプロジェクトタイプは非推奨となった [`create-react-app`](https://github.com/facebook/create-react-app) を利用していました。このガイドでは、より現代的でサポートされた技術(具体的には [Vite](https://vite.dev/))を使用する `ts#website` ジェネレータ を利用してウェブサイトの移行を行います。 移行の一環として、PDK で設定されていた React Router から [TanStack Router](https://tanstack.com/router) に移行し、ルーティングの型安全性を強化します。 #### React ウェブサイトの生成 -`ts#react-website` ジェネレータ を実行して、`packages/website` にウェブサイトプロジェクトをセットアップします: +`ts#website` ジェネレータ を `framework` を `react` に設定して実行し、`packages/website` にウェブサイトプロジェクトをセットアップします: - + #### Cognito 認証の追加 -上記の React ウェブサイトジェネレータは `CloudscapeReactTsWebsiteProject` のようにデフォルトで Cognito 認証をバンドルしていないため、`ts#react-website#auth` ジェネレータ を使用して明示的に追加します。 +上記の React ウェブサイトジェネレータは `CloudscapeReactTsWebsiteProject` のようにデフォルトで Cognito 認証をバンドルしていないため、`ts#website#auth` ジェネレータ を使用して明示的に追加します。 - + これにより、Cognito ホスト型 UI を使用したユーザーログインを確実に行うためのリダイレクトを管理する React コンポーネントが追加されます。また、`packages/common/constructs` に `UserIdentity` という名前の Cognito リソースをデプロイする CDK コンストラクトも追加されます。 @@ -62,6 +62,23 @@ Nx Plugin for AWS では、`connection` ジェ +`@aws-northstar/ui` は `ace-builds` に依存するコードエディタコンポーネントをバンドルしており、Vite が解決できない webpack 固有のインポートを使用しています。ショッピングリストアプリケーションではこのコンポーネントを使用しないため、`packages/website/vite.config.mts` の既存の `build` オプション内の `external` 設定に追加してバンドルから除外します: + +```diff lang="ts" +// packages/website/vite.config.mts + build: { + outDir: '../../dist/packages/website/bundle', + emptyOutDir: true, + reportCompressedSize: true, + commonjsOptions: { + transformMixedEsModules: true, + }, ++ rollupOptions: { ++ external: ['ace-builds/webpack-resolver'], ++ }, + }, +``` + #### コンポーネントとページの移動 [ショッピングリストアプリケーション](https://aws.github.io/aws-pdk/getting_started/shopping_list_app.html#create-new-pages-components) には `CreateItem` コンポーネントと、`ShoppingList`、`ShoppingLists` の2つのページがあります。これらを新しいウェブサイトに移行し、TanStack Router と Nx Plugin for AWS の TypeScript クライアントコードジェネレータを使用するために若干の調整を行います。 @@ -80,12 +97,14 @@ IDE にビルドエラーが表示されますが、以下の変更で新しい #### React Router から TanStack Router への移行 -[ファイルベースルーティング](https://tanstack.com/router/latest/docs/framework/react/routing/file-based-routing) を使用しているため、ローカル開発サーバーでルート設定の自動生成を管理できます。まずローカルサーバーを起動: +[ファイルベースルーティング](https://tanstack.com/router/latest/docs/framework/react/routing/file-based-routing) を使用しているため、ウェブサイトのローカル開発サーバーでルート設定の自動生成を管理できます。 + +ローカルウェブサイトサーバーを起動します: - + :::tip -`serve-local` ターゲットは、`connection` で接続されたAPIのローカルサーバーも起動し、ウェブサイト・モデル・バックエンドに変更があるとホットリロードします。CDKコードを書く前にAPIとウェブサイトをローカルでテストできます! +`dev` ターゲットは、`connection` で接続されたAPIのローカルサーバーも起動し、ウェブサイト・モデル・バックエンドに変更があるとホットリロードします。CDKコードを書く前にAPIとウェブサイトをローカルでテストできます! ::: エラーが表示されますが、ローカルウェブサイトサーバーはポート `4200` で、Smithy API サーバーはポート `3001` で起動します。 diff --git a/docs/src/content/docs/ko/blog/migrating-from-aws-pdk.mdx b/docs/src/content/docs/ko/blog/migrating-from-aws-pdk.mdx index 3a4208b39..ced7b8f26 100644 --- a/docs/src/content/docs/ko/blog/migrating-from-aws-pdk.mdx +++ b/docs/src/content/docs/ko/blog/migrating-from-aws-pdk.mdx @@ -37,7 +37,7 @@ Nx Plugin for AWS로 마이그레이션하면 PDK 대비 다음과 같은 이점 ::: :::caution[특정 시점 가이드] -이 가이드는 특정 시점을 기준으로 작성되었으며 Nx Plugin for AWS의 발전에 따라 업데이트되지 않을 수 있습니다. 이를 보완하기 위해 가이드에서는 `@aws/nx-plugin` 버전을 `0.50.0`으로 고정합니다. 최신 버전을 사용해도 되지만 가이드와 차이가 발생할 수 있습니다. +이 가이드는 특정 시점을 기준으로 작성되었으며 Nx Plugin for AWS의 발전에 따라 업데이트되지 않을 수 있습니다. 이를 보완하기 위해 가이드에서는 `@aws/nx-plugin` 버전을 `1.0.0-rc.33`으로 고정합니다. 최신 버전을 사용해도 되지만 가이드와 차이가 발생할 수 있습니다. ::: ## 예시 마이그레이션: 쇼핑 리스트 애플리케이션 @@ -55,28 +55,7 @@ Nx Plugin for AWS로 마이그레이션하면 PDK 대비 다음과 같은 이점 시작으로 새 프로젝트를 위한 워크스페이스를 생성합니다. 기존 프로젝트를 직접 수정하는 방식보다 깔끔한 결과를 얻을 수 있습니다. Nx 워크스페이스 생성은 PDK의 `MonorepoTsProject` 사용과 동일합니다: - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=pnpm --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=yarn --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=npm --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=bun --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - + 생성된 `shopping-list` 디렉토리를 선호하는 IDE에서 엽니다. diff --git a/docs/src/content/docs/ko/snippets/pdk-migration/example/01-migrate-api.mdx b/docs/src/content/docs/ko/snippets/pdk-migration/example/01-migrate-api.mdx index 82ecc0a70..c85d2344c 100644 --- a/docs/src/content/docs/ko/snippets/pdk-migration/example/01-migrate-api.mdx +++ b/docs/src/content/docs/ko/snippets/pdk-migration/example/01-migrate-api.mdx @@ -26,7 +26,7 @@ OpenAPI나 TypeSpec을 모델링 언어로 사용했거나 Python/Java로 핸들 `ts#smithy-api` 생성기를 실행해 `packages/api`에 API 프로젝트를 설정합니다: - + 이렇게 하면 `model` 프로젝트와 `backend` 프로젝트가 생성됩니다. `model`은 Smithy 모델을 포함하며, `backend`는 서버 구현을 포함합니다. diff --git a/docs/src/content/docs/ko/snippets/pdk-migration/example/02-migrate-website.mdx b/docs/src/content/docs/ko/snippets/pdk-migration/example/02-migrate-website.mdx index e4bfcdef4..efefc0b91 100644 --- a/docs/src/content/docs/ko/snippets/pdk-migration/example/02-migrate-website.mdx +++ b/docs/src/content/docs/ko/snippets/pdk-migration/example/02-migrate-website.mdx @@ -18,15 +18,15 @@ import InstallCommand from '@components/install-command.astro'; #### React 웹사이트 생성 -`packages/website`에 웹사이트 프로젝트를 설정하려면 `ts#react-website` 생성기를 실행하세요: +`packages/website`에 웹사이트 프로젝트를 설정하려면 `framework`를 `react`로 설정하여 `ts#website` 생성기를 실행하세요. 쇼핑 리스트 애플리케이션은 CloudScape 컴포넌트로 구축되었으므로 `ux`도 `cloudscape`로 설정합니다(기본값은 `shadcn`입니다): - + #### Cognito 인증 추가 위 React 웹사이트 생성기는 `CloudscapeReactTsWebsiteProject`처럼 기본적으로 Cognito 인증을 번들로 제공하지 않습니다. 대신 `ts#react-website#auth` 생성기를 통해 명시적으로 추가합니다. - + 이렇게 하면 Cognito 호스팅 UI를 사용하여 사용자가 로그인하도록 적절한 리디렉션을 관리하는 React 컴포넌트가 추가됩니다. 또한 `packages/common/constructs`에 `UserIdentity`라는 Cognito 리소스를 배포하는 CDK 구문이 추가됩니다. @@ -62,6 +62,23 @@ Nx Plugin for AWS에서는 `connection` 생성 +`@aws-northstar/ui`는 Vite가 해결할 수 없는 webpack 전용 임포트를 사용하는 `ace-builds`에 의존하는 코드 에디터 컴포넌트를 번들로 제공합니다. 쇼핑 리스트 애플리케이션에서는 이 컴포넌트를 사용하지 않으므로 `packages/website/vite.config.mts`의 기존 `build` 옵션 내 `external` 구성에 추가하여 번들에서 제외합니다: + +```diff lang="ts" +// packages/website/vite.config.mts + build: { + outDir: '../../dist/packages/website/bundle', + emptyOutDir: true, + reportCompressedSize: true, + commonjsOptions: { + transformMixedEsModules: true, + }, ++ rollupOptions: { ++ external: ['ace-builds/webpack-resolver'], ++ }, + }, +``` + #### 컴포넌트와 페이지 이동 [쇼핑 리스트 애플리케이션](https://aws.github.io/aws-pdk/getting_started/shopping_list_app.html#create-new-pages-components)에는 `CreateItem` 컴포넌트와 `ShoppingList`, `ShoppingLists` 두 페이지가 있습니다. TanStack Router와 Nx Plugin for AWS TypeScript 클라이언트 코드 생성기를 사용하므로 일부 조정을 통해 이를 새 웹사이트로 마이그레이션합니다. @@ -80,12 +97,14 @@ Nx Plugin for AWS에서는 `connection` 생성 #### React Router에서 TanStack Router로 마이그레이션 -[파일 기반 라우팅](https://tanstack.com/router/latest/docs/framework/react/routing/file-based-routing)을 사용하므로 웹사이트 로컬 개발 서버를 사용하여 라우트 구성을 자동으로 생성할 수 있습니다. 로컬 웹사이트 서버를 시작합니다: +[파일 기반 라우팅](https://tanstack.com/router/latest/docs/framework/react/routing/file-based-routing)을 사용하므로 웹사이트 로컬 개발 서버를 사용하여 라우트 구성을 자동으로 생성할 수 있습니다. + +로컬 웹사이트 서버를 시작합니다: - + :::tip -여기서는 `serve-local` 대상을 사용하며, 이는 `connection`으로 연결된 모든 API의 로컬 서버도 시작하고 웹사이트, 모델 또는 백엔드가 변경되면 핫 리로드됩니다! 이렇게 하면 CDK 코드를 작성하기 전에도 API와 웹사이트를 로컬에서 테스트할 수 있습니다. +여기서는 `dev` 대상을 사용하며, 이는 `connection`으로 연결된 모든 API의 로컬 서버도 시작하고 웹사이트, 모델 또는 백엔드가 변경되면 핫 리로드됩니다! 이렇게 하면 CDK 코드를 작성하기 전에도 API와 웹사이트를 로컬에서 테스트할 수 있습니다. ::: 일부 오류가 표시되지만 포트 `4200`에서 로컬 웹사이트 서버와 포트 `3001`에서 로컬 Smithy API 서버가 시작됩니다. diff --git a/docs/src/content/docs/pt/blog/migrating-from-aws-pdk.mdx b/docs/src/content/docs/pt/blog/migrating-from-aws-pdk.mdx index fe8b266d0..44fc338c8 100644 --- a/docs/src/content/docs/pt/blog/migrating-from-aws-pdk.mdx +++ b/docs/src/content/docs/pt/blog/migrating-from-aws-pdk.mdx @@ -6,7 +6,7 @@ authors: - jack --- -import { Steps, Tabs, TabItem } from '@astrojs/starlight/components'; +import { Steps } from '@astrojs/starlight/components'; import Snippet from '@components/snippet.astro'; import CreateNxWorkspaceCommand from '@components/create-nx-workspace-command.astro'; import RunGenerator from '@components/run-generator.astro'; @@ -37,7 +37,7 @@ Note também que alguns recursos do PDK não possuem equivalentes exatos. Consul ::: :::caution[Guia de um momento específico] -Este guia foi escrito para uma versão específica e provavelmente não será atualizado conforme o Nx Plugin for AWS evolui. Para compensar, o guia fixa a versão do `@aws/nx-plugin` em `0.50.0`. Você pode tentar com a versão mais recente, mas podem haver diferenças em relação ao guia. +Este guia foi escrito para uma versão específica e provavelmente não será atualizado conforme o Nx Plugin for AWS evolui. Para compensar, o guia fixa a versão do `@aws/nx-plugin` em `1.0.0-rc.33`. Você pode tentar com a versão mais recente, mas podem haver diferenças em relação ao guia. ::: ## Exemplo de Migração: Aplicação Lista de Compras @@ -55,28 +55,7 @@ A aplicação lista de compras consiste nos seguintes tipos de projeto PDK: Começaremos criando um novo workspace para nosso projeto. Embora mais radical que uma migração in-place, esta abordagem fornece o resultado mais limpo. Criar um workspace Nx é equivalente ao `MonorepoTsProject` do PDK: - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=pnpm --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=yarn --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=npm --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=bun --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - + Abra o diretório `shopping-list` criado em seu IDE favorito. diff --git a/docs/src/content/docs/pt/snippets/pdk-migration/example/01-migrate-api.mdx b/docs/src/content/docs/pt/snippets/pdk-migration/example/01-migrate-api.mdx index cda74a18f..0482fb496 100644 --- a/docs/src/content/docs/pt/snippets/pdk-migration/example/01-migrate-api.mdx +++ b/docs/src/content/docs/pt/snippets/pdk-migration/example/01-migrate-api.mdx @@ -26,7 +26,7 @@ Se você utilizou OpenAPI ou TypeSpec como linguagem de modelagem, ou possui han Execute o gerador `ts#smithy-api` para configurar seu projeto de API em `packages/api`: - + Você notará que isso gera um projeto `model`, além de um projeto `backend`. O projeto `model` contém seu modelo Smithy, e `backend` contém a implementação do servidor. diff --git a/docs/src/content/docs/pt/snippets/pdk-migration/example/02-migrate-website.mdx b/docs/src/content/docs/pt/snippets/pdk-migration/example/02-migrate-website.mdx index 5f7b4176c..99a0b6420 100644 --- a/docs/src/content/docs/pt/snippets/pdk-migration/example/02-migrate-website.mdx +++ b/docs/src/content/docs/pt/snippets/pdk-migration/example/02-migrate-website.mdx @@ -12,21 +12,21 @@ import InstallCommand from '@components/install-command.astro'; O `CloudscapeReactTsWebsiteProject` usado na aplicação de lista de compras configurava um website React com CloudScape e autenticação Cognito integrada. -Este tipo de projeto utilizava [`create-react-app`](https://github.com/facebook/create-react-app), que está agora depreciado. Para migrar o website neste guia, usaremos o gerador `ts#react-website`, que utiliza tecnologias mais modernas e suportadas, como [Vite](https://vite.dev/). +Este tipo de projeto utilizava [`create-react-app`](https://github.com/facebook/create-react-app), que está agora depreciado. Para migrar o website neste guia, usaremos o gerador `ts#website`, que utiliza tecnologias mais modernas e suportadas, como [Vite](https://vite.dev/). Como parte da migração, também substituiremos o React Router configurado pelo PDK por [TanStack Router](https://tanstack.com/router), que adiciona maior segurança de tipos no roteamento do website. #### Gerar um Website React -Execute o gerador `ts#react-website` para configurar seu projeto de website em `packages/website`: +Execute o gerador `ts#website` com `framework` definido como `react` para configurar seu projeto de website em `packages/website`. Como a aplicação de lista de compras é construída com componentes CloudScape, também definimos `ux` como `cloudscape` (o padrão é `shadcn`): - + #### Adicionar Autenticação Cognito -O gerador de website React acima não inclui autenticação Cognito por padrão como o `CloudscapeReactTsWebsiteProject`. Em vez disso, isso é adicionado explicitamente via o gerador `ts#react-website#auth`. +O gerador de website React acima não inclui autenticação Cognito por padrão como o `CloudscapeReactTsWebsiteProject`. Em vez disso, isso é adicionado explicitamente via o gerador `ts#website#auth`. - + Isso adiciona componentes React que gerenciam os redirecionamentos para garantir que os usuários façam login usando a UI hospedada do Cognito. Também adiciona um construct CDK para implantar os recursos do Cognito em `packages/common/constructs`, chamado `UserIdentity`. @@ -62,6 +62,23 @@ O `CloudscapeReactTsWebsiteProject` incluía automaticamente a dependência do ` +O `@aws-northstar/ui` inclui um componente de editor de código que depende de `ace-builds`, usando uma importação específica do webpack que o Vite não consegue resolver. Como nossa aplicação de lista de compras não usa este componente, o excluímos do bundle adicionando-o à configuração `external` dentro das opções `build` existentes em `packages/website/vite.config.mts`: + +```diff lang="ts" +// packages/website/vite.config.mts + build: { + outDir: '../../dist/packages/website/bundle', + emptyOutDir: true, + reportCompressedSize: true, + commonjsOptions: { + transformMixedEsModules: true, + }, ++ rollupOptions: { ++ external: ['ace-builds/webpack-resolver'], ++ }, + }, +``` + #### Mover Componentes e Páginas A [aplicação de lista de compras](https://aws.github.io/aws-pdk/getting_started/shopping_list_app.html#create-new-pages-components) tem um componente chamado `CreateItem` e duas páginas, `ShoppingList` e `ShoppingLists`. Migraremos estes para o novo website, com ajustes necessários devido ao uso do TanStack Router e do gerador de cliente TypeScript do Nx Plugin para AWS. @@ -80,12 +97,14 @@ Nota: agora você verá erros de compilação na IDE. Faremos mais ajustes para #### Migrar de React Router para TanStack Router -Como estamos usando [roteamento baseado em arquivo](https://tanstack.com/router/latest/docs/framework/react/routing/file-based-routing), podemos usar o servidor de desenvolvimento local para gerenciar a configuração de rotas. Inicie o servidor local: +Como estamos usando [roteamento baseado em arquivo](https://tanstack.com/router/latest/docs/framework/react/routing/file-based-routing), podemos usar o servidor de desenvolvimento local do website para gerenciar automaticamente a geração da configuração de rotas. + +Vamos iniciar o servidor local do website: - + :::tip -Usamos o target `serve-local` aqui, que também inicia servidores locais para APIs conectadas via `connection` e recarrega automaticamente se houver mudanças no website, modelo ou backend! Isso permite testar a API e o website localmente antes mesmo de escrever código CDK. +Usamos o target `dev` aqui, que também inicia servidores locais para quaisquer APIs conectadas via `connection` e recarrega automaticamente se houver mudanças no website, modelo ou backend! Isso permite testar a API e o website localmente antes mesmo de escrever código CDK. ::: Você verá alguns erros, mas o servidor local do website deve iniciar na porta `4200`, e o servidor Smithy local na porta `3001`. diff --git a/docs/src/content/docs/vi/blog/migrating-from-aws-pdk.mdx b/docs/src/content/docs/vi/blog/migrating-from-aws-pdk.mdx index 53998f798..575e4aa62 100644 --- a/docs/src/content/docs/vi/blog/migrating-from-aws-pdk.mdx +++ b/docs/src/content/docs/vi/blog/migrating-from-aws-pdk.mdx @@ -6,7 +6,7 @@ authors: - jack --- -import { Steps, Tabs, TabItem } from '@astrojs/starlight/components'; +import { Steps } from '@astrojs/starlight/components'; import Snippet from '@components/snippet.astro'; import CreateNxWorkspaceCommand from '@components/create-nx-workspace-command.astro'; import RunGenerator from '@components/run-generator.astro'; @@ -37,7 +37,7 @@ Cũng lưu ý rằng một số tính năng của PDK không có các tương đ ::: :::caution[Hướng dẫn tại thời điểm cụ thể] -Đây được viết như một hướng dẫn tại thời điểm hiện tại và rất có thể sẽ không được cập nhật khi Nx Plugin for AWS phát triển. Để bù đắp cho điều này, hướng dẫn cố định phiên bản của `@aws/nx-plugin` ở `0.50.0`. Bạn có thể thử với phiên bản mới nhất nếu làm theo, nhưng có thể có một số khác biệt so với hướng dẫn. +Đây được viết như một hướng dẫn tại thời điểm hiện tại và rất có thể sẽ không được cập nhật khi Nx Plugin for AWS phát triển. Để bù đắp cho điều này, hướng dẫn cố định phiên bản của `@aws/nx-plugin` ở `1.0.0-rc.33`. Bạn có thể thử với phiên bản mới nhất nếu làm theo, nhưng có thể có một số khác biệt so với hướng dẫn. ::: ## Ví dụ Di chuyển: Ứng dụng Danh sách Mua sắm @@ -55,28 +55,7 @@ Trong hướng dẫn này, chúng ta sẽ sử dụng [Ứng dụng Danh sách M Để bắt đầu, chúng ta sẽ tạo một workspace mới cho dự án mới của mình. Mặc dù cực đoan hơn so với di chuyển tại chỗ, cách tiếp cận này mang lại cho chúng ta kết quả cuối cùng sạch sẽ nhất. Tạo một Nx workspace tương đương với việc sử dụng `MonorepoTsProject` của PDK: - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=pnpm --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=yarn --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=npm --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=bun --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - + Mở thư mục `shopping-list` mà lệnh này tạo ra trong IDE yêu thích của bạn. diff --git a/docs/src/content/docs/vi/snippets/pdk-migration/example/01-migrate-api.mdx b/docs/src/content/docs/vi/snippets/pdk-migration/example/01-migrate-api.mdx index b3382852c..ed030fe94 100644 --- a/docs/src/content/docs/vi/snippets/pdk-migration/example/01-migrate-api.mdx +++ b/docs/src/content/docs/vi/snippets/pdk-migration/example/01-migrate-api.mdx @@ -26,7 +26,7 @@ Nếu bạn đã sử dụng OpenAPI hoặc TypeSpec làm ngôn ngữ mô hình Chạy generator `ts#smithy-api` để thiết lập dự án api của bạn trong `packages/api`: - + Bạn sẽ nhận thấy điều này tạo ra một dự án `model`, cũng như một dự án `backend`. Dự án `model` chứa mô hình Smithy của bạn, và `backend` chứa triển khai máy chủ của bạn. diff --git a/docs/src/content/docs/vi/snippets/pdk-migration/example/02-migrate-website.mdx b/docs/src/content/docs/vi/snippets/pdk-migration/example/02-migrate-website.mdx index 25db91cd3..cd815aa3e 100644 --- a/docs/src/content/docs/vi/snippets/pdk-migration/example/02-migrate-website.mdx +++ b/docs/src/content/docs/vi/snippets/pdk-migration/example/02-migrate-website.mdx @@ -18,15 +18,15 @@ Trong quá trình di chuyển, chúng ta cũng sẽ chuyển từ React Router #### Tạo một Trang Web React -Chạy trình tạo `ts#react-website` để thiết lập dự án trang web của bạn trong `packages/website`: +Chạy trình tạo `ts#website` với `framework` được đặt thành `react` để thiết lập dự án trang web của bạn trong `packages/website`. Vì ứng dụng danh sách mua sắm được xây dựng với các component CloudScape, chúng ta cũng đặt `ux` thành `cloudscape` (mặc định là `shadcn`): - + #### Thêm Xác Thực Cognito Trình tạo trang web React ở trên không đi kèm xác thực cognito theo mặc định như `CloudscapeReactTsWebsiteProject`, thay vào đó nó được thêm vào một cách rõ ràng thông qua trình tạo `ts#react-website#auth`. - + Điều này thêm các component React quản lý các chuyển hướng phù hợp để đảm bảo người dùng đăng nhập bằng giao diện người dùng được lưu trữ của Cognito. Điều này cũng thêm một construct CDK để triển khai các tài nguyên Cognito trong `packages/common/constructs`, được gọi là `UserIdentity`. @@ -62,6 +62,23 @@ Với Nx Plugin for AWS, tích hợp API được hỗ trợ thông qua +`@aws-northstar/ui` đóng gói một component trình soạn thảo mã phụ thuộc vào `ace-builds`, sử dụng một import đặc thù cho webpack mà Vite không thể phân giải. Vì ứng dụng danh sách mua sắm của chúng ta không sử dụng component này, chúng ta loại trừ nó khỏi bundle bằng cách thêm nó vào cấu hình `external` trong các tùy chọn `build` hiện có trong `packages/website/vite.config.mts`: + +```diff lang="ts" +// packages/website/vite.config.mts + build: { + outDir: '../../dist/packages/website/bundle', + emptyOutDir: true, + reportCompressedSize: true, + commonjsOptions: { + transformMixedEsModules: true, + }, ++ rollupOptions: { ++ external: ['ace-builds/webpack-resolver'], ++ }, + }, +``` + #### Di Chuyển các Component và Page [Ứng dụng danh sách mua sắm](https://aws.github.io/aws-pdk/getting_started/shopping_list_app.html#create-new-pages-components) có một component có tên `CreateItem`, và hai page, `ShoppingList` và `ShoppingLists`. Chúng ta sẽ di chuyển chúng sang trang web mới, thực hiện một số điều chỉnh vì chúng ta đang sử dụng TanStack Router và trình tạo mã client TypeScript của Nx Plugin for AWS. @@ -80,12 +97,14 @@ Lưu ý rằng bây giờ bạn sẽ có một số lỗi build hiển thị tro #### Di Chuyển từ React Router sang TanStack Router -Vì chúng ta đang sử dụng [định tuyến dựa trên file](https://tanstack.com/router/latest/docs/framework/react/routing/file-based-routing), chúng ta có thể sử dụng máy chủ phát triển cục bộ của trang web để quản lý việc tự động tạo cấu hình route. Hãy khởi động máy chủ trang web cục bộ: +Vì chúng ta đang sử dụng [định tuyến dựa trên file](https://tanstack.com/router/latest/docs/framework/react/routing/file-based-routing), chúng ta có thể sử dụng máy chủ phát triển cục bộ của trang web để quản lý việc tự động tạo cấu hình route. + +Hãy khởi động máy chủ trang web cục bộ: - + :::tip -Chúng ta đang sử dụng target `serve-local` ở đây, nó cũng khởi động các máy chủ cục bộ cho bất kỳ API nào đã được kết nối với `connection`, và tự động tải lại nếu trang web, model hoặc backend của bạn thay đổi! Điều này cho phép chúng ta kiểm tra API và trang web cục bộ trước khi chúng ta viết bất kỳ mã CDK nào. +Chúng ta đang sử dụng target `dev` ở đây, nó cũng khởi động các máy chủ cục bộ cho bất kỳ API nào đã được kết nối với `connection`, và tự động tải lại nếu trang web, model hoặc backend của bạn thay đổi! Điều này cho phép chúng ta kiểm tra API và trang web cục bộ trước khi chúng ta viết bất kỳ mã CDK nào. ::: Bạn sẽ thấy một số lỗi, nhưng máy chủ trang web cục bộ sẽ khởi động trên cổng `4200`, cũng như máy chủ Smithy API cục bộ trên cổng `3001`. diff --git a/docs/src/content/docs/zh/blog/migrating-from-aws-pdk.mdx b/docs/src/content/docs/zh/blog/migrating-from-aws-pdk.mdx index 2e1288f1c..06eef3523 100644 --- a/docs/src/content/docs/zh/blog/migrating-from-aws-pdk.mdx +++ b/docs/src/content/docs/zh/blog/migrating-from-aws-pdk.mdx @@ -37,7 +37,7 @@ import InstallCommand from '@components/install-command.astro'; ::: :::caution[特定时间点指南] -本指南基于特定时间点编写,可能不会随 Nx AWS 插件更新而修订。为确保指南有效性,文中固定使用 `@aws/nx-plugin` 的 `0.50.0` 版本。您可尝试使用最新版本,但操作步骤可能与指南存在差异。 +本指南基于特定时间点编写,可能不会随 Nx AWS 插件更新而修订。为确保指南有效性,文中固定使用 `@aws/nx-plugin` 的 `1.0.0-rc.33` 版本。您可尝试使用最新版本,但操作步骤可能与指南存在差异。 ::: ## 示例迁移:购物清单应用 @@ -55,28 +55,7 @@ import InstallCommand from '@components/install-command.astro'; 首先,为新建项目创建工作区。相较于原地迁移,此方法能获得最整洁的最终结果。创建 Nx 工作区相当于使用 PDK 的 `MonorepoTsProject`: - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=pnpm --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=yarn --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=npm --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - - ```bash - npx create-nx-workspace@21.4.1 shopping-list --pm=bun --preset=@aws/nx-plugin@0.50.0 --iacProvider=CDK --ci=skip --analytics=false - ``` - - + 在您常用的 IDE 中打开命令生成的 `shopping-list` 目录。 diff --git a/docs/src/content/docs/zh/snippets/pdk-migration/example/01-migrate-api.mdx b/docs/src/content/docs/zh/snippets/pdk-migration/example/01-migrate-api.mdx index 389529375..6c23e26fe 100644 --- a/docs/src/content/docs/zh/snippets/pdk-migration/example/01-migrate-api.mdx +++ b/docs/src/content/docs/zh/snippets/pdk-migration/example/01-migrate-api.mdx @@ -26,7 +26,7 @@ import InstallCommand from '@components/install-command.astro'; 运行 `ts#smithy-api` 生成器 在 `packages/api` 中创建 API 项目: - + 这会生成 `model` 和 `backend` 项目。`model` 包含 Smithy 模型,`backend` 包含服务端实现。 diff --git a/docs/src/content/docs/zh/snippets/pdk-migration/example/02-migrate-website.mdx b/docs/src/content/docs/zh/snippets/pdk-migration/example/02-migrate-website.mdx index 0f9802234..33821239e 100644 --- a/docs/src/content/docs/zh/snippets/pdk-migration/example/02-migrate-website.mdx +++ b/docs/src/content/docs/zh/snippets/pdk-migration/example/02-migrate-website.mdx @@ -12,21 +12,21 @@ import InstallCommand from '@components/install-command.astro'; 购物清单应用中使用的`CloudscapeReactTsWebsiteProject`配置了一个内置CloudScape和Cognito身份验证的React网站。 -该项目类型基于现已弃用的[`create-react-app`](https://github.com/facebook/create-react-app)。在本迁移指南中,我们将使用`ts#react-website`生成器,它采用了更现代且受支持的技术栈——[Vite](https://vite.dev/)。 +该项目类型基于现已弃用的[`create-react-app`](https://github.com/facebook/create-react-app)。在本迁移指南中,我们将使用`ts#website`生成器,它采用了更现代且受支持的技术栈——[Vite](https://vite.dev/)。 作为迁移的一部分,我们还将从PDK配置的React Router迁移到[TanStack Router](https://tanstack.com/router),这将为网站路由增加额外的类型安全性。 #### 生成React网站 -运行`ts#react-website`生成器在`packages/website`目录下创建网站项目: +运行`ts#website`生成器,将`framework`设置为`react`,在`packages/website`目录下创建网站项目。由于购物清单应用使用CloudScape组件构建,我们还将`ux`设置为`cloudscape`(默认值为`shadcn`): - + #### 添加Cognito身份验证 上述React网站生成器默认不包含Cognito身份验证(与`CloudscapeReactTsWebsiteProject`不同),需要通过`ts#react-website#auth`生成器显式添加: - + 这会添加管理重定向逻辑的React组件以确保用户通过Cognito托管UI登录,同时在`packages/common/constructs`目录下添加名为`UserIdentity`的CDK构造用于部署Cognito资源。 @@ -60,6 +60,23 @@ RuntimeConfig.ensure(this).config = { +`@aws-northstar/ui`捆绑了一个依赖于`ace-builds`的代码编辑器组件,使用了Vite无法解析的webpack特定导入。由于我们的购物清单应用不使用此组件,我们通过在`packages/website/vite.config.mts`中现有的`build`选项内添加`external`配置将其从捆绑包中排除: + +```diff lang="ts" +// packages/website/vite.config.mts + build: { + outDir: '../../dist/packages/website/bundle', + emptyOutDir: true, + reportCompressedSize: true, + commonjsOptions: { + transformMixedEsModules: true, + }, ++ rollupOptions: { ++ external: ['ace-builds/webpack-resolver'], ++ }, + }, +``` + #### 迁移组件与页面 [购物清单应用](https://aws.github.io/aws-pdk/getting_started/shopping_list_app.html#create-new-pages-components)包含`CreateItem`组件及`ShoppingList`、`ShoppingLists`两个页面。迁移时需调整以适应TanStack Router和Nx Plugin for AWS的TypeScript客户端代码生成。 @@ -78,15 +95,19 @@ RuntimeConfig.ensure(this).config = { #### 从React Router迁移到TanStack Router -使用[文件路由](https://tanstack.com/router/latest/docs/framework/react/routing/file-based-routing)时,可通过本地开发服务器自动生成路由配置。启动本地网站服务: +使用[文件路由](https://tanstack.com/router/latest/docs/framework/react/routing/file-based-routing)时,可通过本地开发服务器自动生成路由配置。 + +启动本地网站服务器: - + :::tip -`serve-local`目标会同时启动通过`connection`连接的API本地服务,并在网站、模型或后端变更时热重载!这使得我们无需编写CDK代码即可本地测试API与网站。 +我们在这里使用`dev`目标,它还会启动通过`connection`连接的任何API的本地服务器,并在网站、模型或后端发生变化时热重载!这使我们能够在编写任何CDK代码之前就在本地测试API和网站。 ::: -服务启动后(网站端口`4200`,Smithy API端口`3001`),按以下步骤迁移路由: +您会看到一些错误,但本地网站服务器应该会在端口`4200`上启动,Smithy API本地服务器在端口`3001`上启动。 + +按以下步骤在`routes/index.tsx`和`routes/$shoppingListId.tsx`中迁移到TanStack Router: