Angular CLI로 Angular 유니버설 앱 만들기

에서 최신 버전을 얻을 수 있습니다.https://leanpub.com/angular-universal

AngularInDepth 가 Medium에서 멀어지고 있습니다. 최신 기사는 새로운 플랫폼 inDepth.dev 에서 호스팅됩니다 . 심도 있는 움직임에 참여해주셔서 감사합니다!

Angular CLI 는 node 를 사용하여 서버 플랫폼용 앱을 빌드 하는 기능을 1.3.0-rc.0 버전과 함께 방금 도입했습니다 . 다음은 그것을 사용하는 몇 가지 첫 번째 팁입니다.

Angular Universal을 처음 사용하는 경우 이전 기사를 소개로 읽을 수 있습니다.
—https://medium.com/@feloy/angular-v4-universal-demystified-f06a576d6ca2
—https://medium.com/@feloy/building-a-static-website-with-angular-universal-a1acc49e26e5
—https://medium.com/@feloy/building-a-dynamic-website-with-angular-universal-f8dd7bffb667

이 기사의 모든 소스 코드는 github 저장소에서 찾을 수 있습니다.https://github.com/feloy/ng-cli-universal

1.3.0-RC.0 버전을 설치하고 새 프로젝트를 생성해야 합니다.

$ npm uninstall -g @angular/cli
$ npm cache clean
$ npm install -g @angular/[email protected]
$ ng new ng-cli-universal

JIT 컴파일 사용

먼저 , .angular-cli.json앱 구성에 맞게 파일을 수정해야 합니다. 더 이상 폴리필을 사용하지 않고(노드에 필요하지 않음) server플랫폼을 표시합니다.

"apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.scss"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      },
      "platform": "server"
    }
  ],

$ npm install --save @angular/platform-server

// src/main.ts
import { enableProdMode } from '@angular/core';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
  enableProdMode();
}
export { AppModule } from './app/app.module';

// src/tsconfig.app.json
{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "baseUrl": "./",
    "module": "es2015",
    "types": []
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ],
  "angularCompilerOptions": {
    "entryModule": "app/app.module#AppModule"
  }
}

// src/app/app.module.ts
import { ServerModule } from '@angular/platform-server';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ 
      appId: 'ng-cli-universal' 
    }), 
    ServerModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

$ ng build

// ./index.js
require('zone.js/dist/zone-node');
require('reflect-metadata');
const fs = require('fs');
const { AppModule } = require('./dist/main.bundle');
const { renderModule } = require('@angular/platform-server');
renderModule(AppModule, {
    url: '/',
    document: '<app-root></app-root>'
}).then(html => {
    fs.writeFileSync('dist/index.html', html);
});

$ node index.js

AOT 컴파일 사용

AOT를 사용하여 앱을 빌드할 수도 있습니다.

$ ng build -aot

// ./index.js
require('zone.js/dist/zone-node');
require('reflect-metadata');
const fs = require('fs');
const { AppModuleNgFactory } = require('./dist/main.bundle');
const { renderModuleFactory } = require('@angular/platform-server');
renderModuleFactory(AppModuleNgFactory, {
    url: '/',
    document: '<app-root></app-root>'
}).then(html => {
    fs.writeFileSync('dist/index.html', html);
});

이전 단계(JIT 및 AOT 컴파일 모두 사용)를 통해 서버 측에서 HTML 페이지를 렌더링하는 앱을 얻습니다. 브라우저에서 렌더링된 HTML 페이지를 로드하면 정적 웹 페이지만 가져옵니다. 브라우저 앱도 빌드하고 서버에서 브라우저 앱으로 전환하는 방법을 살펴보겠습니다.

다음 코드는 Angular CLI로 생성된 새로운 앱을 기반으로 합니다. 이전에 변경한 내용을 되돌리거나 앱을 처음부터 지우고 다시 만들 수 있습니다 ng new ng-cli-universal.

@angular/platform-server패키지를 다시 설치해야 합니다.

$ npm install --save @angular/platform-server

// .angular-cli.json
"apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    },
    {
      "name": "ssr",
      "root": "src",
      "outDir": "dist-ssr",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "main": "main-ssr.ts",
      "tsconfig": "tsconfig.app-ssr.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      },
      "platform": "server"
    }
  ],

또한 특정 main-ssr.ts, src/tsconfig.app-ssr.json및 src/app/app.server.module.ts이전에 생성해야 하는 파일을 사용하고 있습니다.

// src/main-ssr.ts
export { AppServerModule } from './app/app.server.module';
// src/app/app.server.module.ts
import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { AppComponent } from './app.component';
import { AppModule } from './app.module';
@NgModule({
  imports: [
          AppModule,
          ServerModule
  ],
  bootstrap: [
          AppComponent
  ]
})
export class AppServerModule {}
// src/tsconfig.app-ssr.json
{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "baseUrl": "./",
    "module": "commonjs",
    "types": []
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ],
  "angularCompilerOptions": {
    "entryModule": "app/app.server.module#AppServerModule"
  }
}

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ 
      appId: 'ng-cli-universal' 
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

$ ng build -aot 
$ ng build -aot -app ssr

require('zone.js/dist/zone-node');
require('reflect-metadata');
const fs = require('fs');
const { AppModuleNgFactory } = require('./dist-ssr/main.bundle');
const { renderModuleFactory } = require('@angular/platform-server');
renderModuleFactory(AppModuleNgFactory, {
    url: '/',
    document: fs.readFileSync('dist/index.html', 'utf8')
}).then(html => {
    fs.writeFileSync('dist-ssr/index.html', html);
});

이 시점에서 index.js파일은 앱의 홈 페이지만 (서버 측) 렌더링할 수 있습니다. 앱의 모든 페이지를 렌더링할 수 있도록 스크립트를 조정할 수 있습니다. 당신은 볼 수 있습니다https://medium.com/@feloy/building-a-dynamic-website-with-angular-universal-f8dd7bffb667렌더링할 URL을 인수로 가져오는 스크립트의 몇 가지 예를 얻으려면

해피 유니버셜!

Suggested posts

내가 가장 많이 사용하는 코딩 리소스

내가 가장 많이 사용하는 코딩 리소스

이번 주에 저는 일일 이메일 목록의 회원으로부터 이메일을 받았습니다. 그들은 알고 싶어했습니다. 매일, 매주, 매월 어떤 리소스를 방문합니까? 좋은 질문입니다! 제 작업 흐름과 제가 사용하는 주요 리소스에 대한 통찰력을 공유하게 되어 기쁩니다.

Lit 라이브러리 시리즈 — 1: lit-html 라이브러리에 대한 심층 분석

Lit 라이브러리 시리즈 — 1: lit-html 라이브러리에 대한 심층 분석

이 블로그 시리즈의 목적은 Lit 라이브러리를 깊이 탐구하고 Lit 라이브러리의 고유한 기능과 시장의 다른 라이브러리 및 프레임워크와 차별화되는 방법을 포괄적으로 이해하는 것입니다. 이 시리즈는 1과 같은 주제를 다루는 세 부분으로 나뉩니다.

Related posts

위험한 대화

위험한 대화

우리가 이 행성에서 계속 번성하고 싶다면 위험한 대화를 해야 할 것입니다. 우리가 한 것, 우리가 하고 있는 것, 그리고 현재 우리가 계속하기로 설정한 것(또는 할 계획인 것)에 도전하는 것들.

느린 침식: 사람들이 경력을 낭비하는 방식 공개

느린 침식: 사람들이 경력을 낭비하는 방식 공개

오늘날과 같이 급변하고 경쟁이 치열한 세상에서 경력은 개인의 성장, 재정적 안정 및 전반적인 삶의 만족도에 중요한 역할을 합니다. 그러나 많은 사람들은 침체와 불만족의 끊임없는 순환에 휩싸여 직업 생활에서 점차 쇠퇴하고 있습니다.

더 이상 암호가 없습니다. 암호가 암호를 대체하는 방법

더 이상 암호가 없습니다. 암호가 암호를 대체하는 방법

모호함을 피하기 위해 다음 용어가 사용됩니다. 인증자; 로그인 웹사이트를 만드는 데 사용되는 휴대폰 사용자가 로그인 요청 서비스를 만들기 위해 사용하는 웹사이트 또는 애플리케이션 주어진 서비스를 제공하는 벤더 예.

네트워크 TV 트위터

네트워크 TV 트위터

낡은 것이 다시 새 것이 되고, 번쩍이던 것이 이제는 무디게 느껴진다. JNCO 청바지가 1990년대 후반의 다른 패션과 함께 시내의 쿨한 아이들 사이에서 컴백하는 것에 대해 말하는 것이 아닙니다.