嗨我正在使用带有通用的角度2。
我正在尝试这个。
首先我创建一个新项目:
ng new universaldemo.
我安装了这些软件包:
npm install --save @angular/platform-server @nguniversal/module-map-ngfactory-loader ts-loader @nguniversal/express-engine
。
这是我的app.module.ts
:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule.withServerTransition({ appId: 'universaldemo' }),
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
这是我的app.server.module.ts
import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { ModuleMapLoaderModule } from '@nguniversal/module-map-ngfactory-loader';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
@NgModule({
imports: [
AppModule,
ServerModule,
ModuleMapLoaderModule
],
providers: [
// Add universal-only providers here
],
bootstrap: [ AppComponent ],
})
export class AppServerModule {}
这是我的server.ts
:
// These are important and needed before anything else
import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import { enableProdMode } from '@angular/core';
import * as express from 'express';
import { join } from 'path';
// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();
// Express server
const app = express();
const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), 'dist');
// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/server/main.bundle');
// Express Engine
import { ngExpressEngine } from '@nguniversal/express-engine';
// Import module map for lazy loading
import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';
app.engine('html', ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
provideModuleMap(LAZY_MODULE_MAP)
]
}));
app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));
// TODO: implement data requests securely
app.get('/api/*', (req, res) => {
res.status(404).send('data requests are not supported');
});
// Server static files from /browser
app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));
// All regular routes use the Universal engine
app.get('*', (req, res) => {
res.render(join(DIST_FOLDER, 'browser', 'index.html'), { req });
});
// Start up the Node server
app.listen(PORT, () => {
console.log(`Node server listening on http://localhost:${PORT}`);
});
这是我的webpack.server.config.js
:
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: { server: './server.ts' },
resolve: { extensions: ['.js', '.ts'] },
target: 'node',
// this makes sure we include node_modules and other 3rd party libraries
externals: [/(node_modules|main\..*\.js)/],
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].js'
},
module: {
rules: [{ test: /\.ts$/, loader: 'ts-loader' }]
},
plugins: [
// Temporary Fix for issue: https://github.com/angular/angular/issues/11580
// for 'WARNING Critical dependency: the request of a dependency is an expression'
new webpack.ContextReplacementPlugin(
/(.+)?angular(\\|\/)core(.+)?/,
path.join(__dirname, 'src'), // location of your src
{} // a map of your routes
),
new webpack.ContextReplacementPlugin(
/(.+)?express(\\|\/)(.+)?/,
path.join(__dirname, 'src'),
{}
)
]
};
最后我创建tsconfig.server.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"
}
}
以下行已添加到我的package.json
:
"scripts": {
...
"build:universal": "npm run build:client-and-server-bundles && npm run webpack:server",
"serve:universal": "node dist/server.js",
"build:client-and-server-bundles": "ng build --prod && ng build --prod --app 1 --output-hashing=false",
"webpack:server": "webpack --config webpack.server.config.js --progress --colors"
...
}
这是我的angular-Cli.json
:
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"project": {
"name": "angularuniversaldemo"
},
"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"
}
}
],
"e2e": {
"protractor": {
"config": "./protractor.conf.js"
}
},
"lint": [
{
"project": "src/tsconfig.app.json",
"exclude": "**/node_modules/**"
},
{
"project": "src/tsconfig.spec.json",
"exclude": "**/node_modules/**"
},
{
"project": "e2e/tsconfig.e2e.json",
"exclude": "**/node_modules/**"
}
],
"test": {
"karma": {
"config": "./karma.conf.js"
}
},
"defaults": {
"styleExt": "css",
"component": {}
}
}
我尝试创建构建并提供我的应用程序:
npm run build:universal
npm run serve:universal.
不创建构建和运行应用程序。
我收到了这些错误:
1
ERROR in Error: Metadata version mismatch for module F:/anitha/projects/Universal/universaldemo/node_modules/@angular/platform-server/platform-server.d.ts, found version 4, expected 3...
npm ERR! Windows_NT 10.0.15063....
2
Cannot find name 'process' and Cannot find name 'require'.
3
Unable to find app with name or index. Verify the configuration in `.angular-cli.json`
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! angularuniversaldemo@0.0.0 build:client-and-server-bundles: `ng build --prod && ng build --prod --app 1 --output-hashing=false`
npm ERR! Exit status 1
我需要运行并构建我的应用程序。我怎么能这样做?
请建议我,
感谢。
答案 0 :(得分:2)
看起来您使用的是平台服务器模块的错误版本。
您可以尝试直接在此文件
中强制项目中所需的依赖项版本您还必须使用ts-node
启动server.ts脚本,而不是仅node
:
npm install ts-node --save
并使用以下内容更改package.json
脚本
"serve:universal": "ts-node dist/server.ts
要区分构建,您可以在angular-cli.json
文件中定义多个应用,如下所示:
"apps": [
{
"name": "app",
"root": "src",
"outDir": "dist",
...
},
{
"name": "universal",
"root": "src",
"outDir": "dist-universal",
...
},
{
"name": "server",
"platform": "server",
"root": "src",
...
}
],
然后,您可以选择使用--app
标记启动的应用:
ng build/serve --app app/universal/server
该名称必须与angular-cli.json
文件中的名称一致,因此在您的情况下,您的应用必须命名为1
。
或者,如果您只需要一个app / config,则可以运行ng build (--prod/aot...)
而不使用--app
请注意dist
文件夹的路径。检查以下参数:
tsconfig ** JSON:
...
"genDir": "../dist"
...
角cli.json:
...
"outDir": "./dist",
...
这些路径是相对路径,必须与server.ts
文件