Angular Cli는 이제 버전 1.3.0-rc.0 이상에서이 기능을 지원합니다.
당신은
npm install -g @angular/cli
Setup Instructions from Angular Cli Wiki on Universal Rendering
I have a demo app which can be found on GitHub
Source:https://github.com/joejordanbrown/angular-cli-universal
Live Demo:https://uixd.co.uk/open-source-software/angular-cli-universal/
1 단계를 사용하여이 버전을 설치할 수 있습니다
: 만들기 새로운 각도 CLI 응용 프로그램
$ ng new angular-cli-universal
2 단계 :
이 프로젝트에 각도/플랫폼 서버 @ 설치 각도/플랫폼 서버 @ 설치합니다. 프로젝트에서 다른 @angular 패키지와 동일한 버전을 사용해야합니다.
$ npm install --save-dev @angular/platform-server
또는
$ yarn add @angular/platform-server
3 단계 :
당신은 추가하여 유니버설와 AppModule 호환되도록 할 필요가있는 첫번째 일은 렌더링 우주에 대한 귀하의 응용 프로그램을 준비합니다.withServerTransition()와 BrowserModule 가져 오기에 응용 프로그램 ID :
SRC/응용 프로그램/app.module.ts : 서버에서 실행하는 경우
@NgModule({
bootstrap: [AppComponent],
imports: [
// Add .withServerTransition() to support Universal rendering.
// The application ID can be any identifier which is unique on
// the page.
BrowserModule.withServerTransition({appId: 'my-app'}),
...
],
})
export class AppModule {}
다음, 응용 프로그램을 위해 특별히 모듈을 만들 수 있습니다. 이 모듈을 AppServerModule이라고 부르는 것이 좋습니다.
이 예제 파일에 app.module.ts과 함께 그것을 배치라는 이름의 app.server.module.ts :
SRC/응용 프로그램/app.server.module.ts :
import {NgModule} from '@angular/core';
import {ServerModule} from '@angular/platform-server';
import {AppModule} from './app.module';
import {AppComponent} from './app.component';
@NgModule({
imports: [
// The AppServerModule should import your AppModule followed
// by the ServerModule from @angular/platform-server.
AppModule,
ServerModule,
],
// Since the bootstrapped component is not inherited from your
// imported AppModule, it needs to be repeated here.
bootstrap: [AppComponent],
})
export class AppServerModule {}
4 단계 : 유니버스의 주요 파일을 작성 그것을
을 구축 할 수있는 서버 기본 파일 및 tsconfig 만들기 알 번들. 이 파일은 AppServerModule 만 내보내면됩니다. 그것은 src에 들어갈 수 있습니다.
SRC/main.server.ts :
export {AppServerModule} from './app/app.server.module';
복사 tsconfig.app.json이 tsconfig-server.json 및 빌드로 변경이 예는이 파일 main.server.ts를 호출 "commonjs"의 "모듈"타겟.
"angularCompilerOptions"에 대한 섹션을 추가하고 기호 이름이 들어있는 해시 (#)가있는 가져 오기 경로로 지정된 AppServerModule에 "entryModule"을 설정하십시오. 이 예에서는 src/app/app.server.module # AppServerModule입니다.
SRC/tsconfig.server.json :
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"baseUrl": "./",
// Set the module format to "commonjs":
"module": "commonjs",
"types": []
},
"exclude": [
"test.ts",
"**/*.spec.ts"
],
// Add "angularCompilerOptions" with the AppServerModule you wrote
// set as the "entryModule".
"angularCompilerOptions": {
"entryModule": "app/app.server.module#AppServerModule"
}
}
5 단계하십시오 NodeJS 서버 파일 당신은 렌더링 및 응용 프로그램을 제공하는 NodeJS 서버를 만들 필요가 을 만듭니다. 이 예제에서는 express를 사용합니다.
설치를 명시하고 압축
$ npm install --save express compression @nguniversal/express-engine
또는
$ yarn add express compression @nguniversal/express-engine
SRC/express.server.js :
const path = require('path');
const fs = require('fs');
const express = require('express');
const compression = require('compression');
const ngExpressEngine = require('@nguniversal/express-engine').ngExpressEngine;
require('zone.js/dist/zone-node');
require('rxjs/add/operator/filter');
require('rxjs/add/operator/map');
require('rxjs/add/operator/mergeMap');
var hash;
fs.readdirSync(__dirname).forEach(file => {
if (file.startsWith('main')) {
hash = file.split('.')[1];
}
});
const AppServerModuleNgFactory = require('./main.' + hash + '.bundle').AppServerModuleNgFactory;
const app = express();
const port = Number(process.env.PORT || 8080);
app.engine('html', ngExpressEngine({
baseUrl: 'http://localhost:' + port,
bootstrap: AppServerModuleNgFactory
}));
app.set('view engine', 'html');
app.set('views', path.join(__dirname, '/../browser'));
app.use(compression());
app.use('/', express.static(path.join(__dirname, '/../browser'), {index: false}));
app.get('/*', function (req, res) {
res.render('index', {
req: req,
// res: res
});
});
app.listen(port, function() {
console.log(`Listening at ${port}`);
});
6 단계 : .angular-cli.json에서 새 프로젝트 만들기
.angular-cli.json에는 키 "apps"아래에 배열이 있습니다. 클라이언트 응용 프로그램의 구성을 거기에 복사 한 다음 추가 키 "platform"을 "server"로 설정하여 배열에 새 항목으로 붙여 넣으십시오.
그런 다음 서버에서 필요하지 않은 "polyfills"키를 제거하고 2 단계에서 작성한 파일을 가리 키도록 "main"및 "tsconfig"를 조정하십시오. 마지막으로 "outDir"을 a 새로운 위치 (이 예제는 dist/server를 사용합니다).
.angular-cli.json :
{
...
"apps": [
{
// Keep your original application config the same apart from changing outDir to dist/browser.
// It will be app 0.
"outDir": "dist/browser",
},
{
// This is your server app. It is app 1.
"platform": "server",
"root": "src",
// Build to dist/server instead of dist. This prevents
// client and server builds from overwriting each other.
"outDir": "dist/server",
"assets": [
"assets",
"favicon.ico",
"express.server.js"
],
"index": "index.html",
// Change the main file to point to your server main.
"main": "main.server.ts",
// Remove polyfills.
// "polyfills": "polyfills.ts",
"test": "test.ts",
// Change the tsconfig to point to your server config.
"tsconfig": "tsconfig.server.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"
}
}
],
...
}
당신이 당신의 애플리케이션 서버 번들을 구축 할 수 있어야 번들 완전한 다음 단계로
구축, --app 플래그를 사용하여 CLI에 서버 번들을 작성하고 .angular-cli.json의 "apps"배열에서 1의 인덱스를 참조하도록 지정합니다.
# This builds the client application in dist/browser/
$ ng build --prod
...
# This builds the server bundle in dist/server/
$ ng build --prod --app 1
Date: 2017-07-24T22:42:09.739Z
Hash: 9cac7d8e9434007fd8da
Time: 4933ms
chunk {0} main.988d7a161bd984b7eb54.bundle.js (main) 9.49 kB [entry] [rendered]
chunk {1} styles.d41d8cd98f00b204e980.bundle.css (styles) 0 bytes [entry] [rendered]
설명서를 출시되었습니다 명시 서버
$ node dist/server/express.server.js
View the Angular Cli Wiki for more details https://github.com/angular/angular-cli/wiki/stories-universal-rendering
기존 프로젝트가 필요하고 현재 안정적이지 않습니다 ... –
각도 보편성은 매우 미숙합니다. 나는 또한 안정적인 출시를 기다리고있다. –
@VinayPandya, cli 프로젝트와 함께 범용 앵글을 사용하는 방법을 찾았습니까? 모든 입력이 도움이 될 것입니다. –