DEV Community

Cover image for Integración de una aplicación de Angular con Fresh Framework: guía fácil
Rafael Mejia
Rafael Mejia

Posted on

Integración de una aplicación de Angular con Fresh Framework: guía fácil

Si está aquí, tal vez esté donde comencé, para este tutorial asumo que ya tiene Deno y Angular instalados, este proceso también se aplica a Ionic.

Comencemos con esta integración. Solo necesita crear un nuevo proyecto con Deno. No importa si ya tiene un proyecto creado, pero tenga en cuenta que necesitaremos agregar varios archivos a la carpeta de activos más adelante. Verás.

Inicie el proyecto con Fresh usando Deno:

deno run -A -r https://fresh.deno.dev fresh-angular && cd fresh-angular
Enter fullscreen mode Exit fullscreen mode

Complete las preguntas iniciales para configurar su proyecto, ahora, comience un nuevo proyecto con Angular o Ionic (en mi caso usaré Ionic 7 con Angular 15):

ionic start my-project tabs --type=angular --no-git
Enter fullscreen mode Exit fullscreen mode

Ahora su estructura de archivos puede verse así:
Una imagen de cómo puede verse la estructura de su proyecto

Integración

Ahora debemos hacer algunos cambios, dentro de la carpeta routes, crear una carpeta llamada app, y crear un archivo llamado [...app].ts y pegar este código dentro del archivo recién creado:

import { Handlers } from '$fresh/server.ts'

export const handler: Handlers = {
    async GET() {

        const filePath = new URL('file://'+Deno.cwd()+'/static/index.html').pathname;
        let fileSize;
        try {
          fileSize = (await Deno.stat(filePath)).size;
        } catch (e) {
          return new Response(null, { status: 500 });
        }
        const body = (await Deno.open(filePath)).readable;
        const resp = new Response(body);
        resp.headers.set("content-length", fileSize.toString());
        resp.headers.set("content-type", "text/html; charset=utf-8");
        return resp;

    }
}
Enter fullscreen mode Exit fullscreen mode

¡No empieces el proyecto todavía!

Abra su terminal VSCode y escriba este comando en él: cd App && ng build --configuration=production

Dentro de su carpeta /App ahora debe ver una carpeta llamada www, ahora vamos a crear un ayudante para mover esa carpeta a nuestra carpeta /static.

En su directorio raíz, cree un archivo llamado sync.ts y pegue el siguiente código:

let htmlContent = await Deno.readTextFile('./App/www/index.html');
const entries: string[] = [];

console.log('Checking directories...')
for await (const dirEntry of Deno.readDir('./App/www')) {
   if(dirEntry.name.endsWith('.js')) entries.push(`<script src="${dirEntry.name}" type="module"></script>`);
}

htmlContent = htmlContent.replace(/<script src=".+" type="module"><\/script>/gm, entries.toString()).replace('<base href="/">', '<base href="/app">');

const sourceDir = "./App/www";
const destinationDir = "./static";

console.log('Removing old files...');
for await (const dirEntry of Deno.readDir('./static')) {
    if(dirEntry.name !== 'save') Deno.removeSync('./static/' + dirEntry.name, { recursive: true });
 }

console.log('Updating files...');
for await (const dirEntry of Deno.readDir(sourceDir)) {
  const sourcePath = `${sourceDir}/${dirEntry.name}`;
  const destinationPath = `${destinationDir}/${dirEntry.name}`;

  await Deno.rename(sourcePath, destinationPath);
}

console.log('Rewriting index.html...')
await Deno.writeTextFile('./static/index.html', htmlContent);
Enter fullscreen mode Exit fullscreen mode

Antes de finalizar, debes ir a tu deno.json y agregar este script dentro del objeto task:

"sync": "cd App && ng build --configuration=production && cd .. && deno run -A sync.ts"
Enter fullscreen mode Exit fullscreen mode

Finalmente, si llega aquí, simplemente ejecute en su terminal el proyecto raíz deno task start y siga el enlace que se muestra en el terminal, generalmente http://localhost:8000 o escriba manualmente en la barra de búsqueda de su navegador http://localhost:8000/app para ver cómo funciona su aplicación Angular dentro de su Fresh Project.

La aplicación angular que se ejecuta dentro de Fresh

¡Espero que esta publicación te ayude!

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay