首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何设置Angular cli + Angular universal?

如何设置Angular cli + Angular universal?
EN

Stack Overflow用户
提问于 2016-12-12 17:56:07
回答 3查看 6.6K关注 0票数 10

有没有人有使用angular cli项目安装angular universal的经验?

我试着遵循下面的指南:

https://universal.angular.io/quickstart/

但在我这样做之后:

代码语言:javascript
复制
typings install node express body-parser serve-static express-serve-static-core mime --global

我得到了错误:

代码语言:javascript
复制
typings INFO globaldependencies "express" lists global dependencies on "node" that must be installed manually
typings ERR! message Unable to find "node" ("npm") in the registry.
typings ERR! message However, we found "node" for 2 other sources: "dt" and "env"
typings ERR! message You can install these using the "source" option.
typings ERR! message We could use your help adding these typings to the registry: https://github.com/typings/registry
typings ERR! caused by https://api.typings.org/entries/npm/node/versions/latest responded with 404, expected it to equal 200
typings ERR! 
typings ERR! cwd /home/universal
typings ERR! system Linux 3.10.17
typings ERR! command "/usr/bin/node" "/usr/bin/typings" "install" "node" "express" "body-parser" "serve-static" "express-serve-static-core" "mime" "--global"
typings ERR! node -v v4.2.4
typings ERR! typings -v 2.0.0
typings ERR! 
typings ERR! If you need help, you may report this error at:
typings ERR!   <https://github.com/typings/typings/issues>
EN

回答 3

Stack Overflow用户

发布于 2017-07-30 09:11:16

Angular Cli现在在版本1.3.0-rc.0及更高版本中支持此功能。

您可以使用以下命令安装此版本

npm install -g @angular/cli

来自上的Angular Cli Wiki的

设置说明

我有一个演示应用程序,可以在GitHub上找到

来源: https://github.com/joejordanbrown/angular-cli-universal

现场演示: https://uixd.co.uk/open-source-software/angular-cli-universal/

第一步:创建新的Angular客户端应用程序

代码语言:javascript
复制
$ ng new angular-cli-universal

第2步:安装@angular/平台服务器

将@angular/platform-server安装到您的项目中。确保您在项目中使用与其他@angular包相同的版本。

代码语言:javascript
复制
$ npm install --save-dev @angular/platform-server

代码语言:javascript
复制
$ yarn add @angular/platform-server

第3步:为通用渲染准备应用程序

您需要做的第一件事是通过将.withServerTransition()和应用程序ID添加到您的BrowserModule导入中,使您的AppModule与通用兼容:

src/app/app.module.ts:

代码语言:javascript
复制
@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/app.server.module.ts:

代码语言:javascript
复制
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构建它的

为您的Universal包创建主文件。这个文件只需要导出您的AppServerModule。它可以放在src中。此示例将此文件命名为main.server.ts:

src/main.server.ts:

代码语言:javascript
复制
export {AppServerModule} from './app/app.server.module';

将tsconfig.app.json复制到tsconfig-server.json,并将其更改为使用“模块”目标"commonjs“进行构建。

为"angularCompilerOptions“添加一个部分,并将"entryModule”设置为您的AppServerModule,指定为包含符号名称的散列(#)的导入路径。在本例中,这将是src/app/app.server.module#AppServerModule。

src/tsconfig.server.json:

代码语言:javascript
复制
{
  "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。

安装express和压缩

代码语言:javascript
复制
$ npm install --save express compression @nguniversal/express-engine

代码语言:javascript
复制
$ yarn add express compression @nguniversal/express-engine

src/express.server.js:

代码语言:javascript
复制
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“键-服务器上不需要的那些,并调整"main”和"tsconfig“以指向您在步骤2中编写的文件。最后,将"outDir”调整为一个新位置(本例使用dist/ server )。

.angular-cli.json:

代码语言:javascript
复制
{
  ...
  "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:

代码语言:javascript
复制
# 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]

启动express服务器

代码语言:javascript
复制
$ node dist/server/express.server.js

查看Angular Cli维基了解更多详细信息https://github.com/angular/angular-cli/wiki/stories-universal-rendering

票数 10
EN

Stack Overflow用户

发布于 2016-12-14 01:04:38

您可以使用https://github.com/devCrossNet/angular-cli中的universal-cli

它是angular-cli的分支,但它使用的是angular universal。

在安装了npm install -g universal-cli之后,使用

ung new PROJECT_NAME --universal

那么这个项目应该已经准备好了。

cd PROJECT_NAME ung serve

我还没有使用现有的angular-cli项目进行测试,但也许ung init --universal可以提供帮助。

票数 1
EN

Stack Overflow用户

发布于 2017-08-20 09:28:28

现在Angular-cli 1.3已经发布,文档已经更新,可以通过指南here来涵盖通用。有一个指南和示例,可以让它与Universal + material 2和Express服务器here一起工作。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41098155

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档