首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角SSR + webpack

角SSR + webpack
EN

Stack Overflow用户
提问于 2020-11-11 09:34:33
回答 1查看 1.1K关注 0票数 0

我在做一个有角度的喷射器,

版本:

-Angular CLI: 8.3.29

-Node: 12.14.1

-Angular: 8.2.14

我需要在它上应用侧渲染,我使用下面的命令在我的项目中设置角大学

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

在解决了很多问题后(建筑,闪烁,双加载页面.)我现在可以在我的本地环境中启动它

代码语言:javascript
复制
build:ssr && serve:ssr

但是,当我尝试在生产服务器上部署它时,当我尝试用node /dist/server/main.js启动服务器时,在产品服务器上构建项目之后

我得到了以下错误

错误:找不到模块“zone.js/dist/zone-节点”

我在论坛上搜索,发现我必须与webpack一起构建服务器端代码。

所以我把我的package.json更新到

代码语言:javascript
复制
"dev:ssr": "ng run my-app-name:serve-ssr",
"serve:ssr": "node dist/server.js",
"build:client-and-server-bundles": "ng build --prod && ng run my-app-name:server:production",
"build-wp:ssr": "npm run build:client-and-server-bundles && npm run webpack:server",
"webpack:server": "webpack --config webpack.server.config.js --progress --colors"

webpack.server.config.js

代码语言:javascript
复制
const path = require('path');
const webpack = require('webpack');

module.exports = {
  mode: 'none',
  entry: {
    // This is our Express server for Dynamic universal
    server: './server.ts'
  },
  externals: {
    './dist/server/main': 'require("./server/main")'
  },
  target: 'node',
  resolve: { extensions: ['.ts', '.js'] },
  optimization: {
    minimize: false
  },
  output: {
    // Puts the output at the root of the dist folder
    path: path.join(__dirname, 'dist'),
    filename: '[name].js'
  },
  module: {
    noParse: /polyfills-.*\.js/,
    rules: [
      { test: /\.ts$/, loader: 'ts-loader' },
      {
        // Mark files inside `@angular/core` as using SystemJS style dynamic imports.
        // Removing this will cause deprecation warnings to appear.
        test: /(\\|\/)@angular(\\|\/)core(\\|\/).+\.js$/,
        parser: { system: true },
      },
    ]
  },
  plugins: [
    new webpack.ContextReplacementPlugin(
      // fixes WARNING Critical dependency: the request of a dependency is an expression
      /(.+)?angular(\\|\/)core(.+)?/,
      path.join(__dirname, 'src'), // location of your src
      {} // a map of your routes
    ),
    new webpack.ContextReplacementPlugin(
      // fixes WARNING Critical dependency: the request of a dependency is an expression
      /(.+)?express(\\|\/)(.+)?/,
      path.join(__dirname, 'src'),
      {}
    )
  ]
};

server.ts

代码语言:javascript
复制
import 'zone.js/dist/zone-node';

import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import { join } from 'path';

import { AppServerModule } from './src/main.server';
import { APP_BASE_HREF } from '@angular/common';
import { existsSync } from 'fs';

// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
  const server = express();
  const distFolder = join(process.cwd(), 'dist/browser');
  const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';


  const DIST_FOLDER = join(process.cwd(), 'dist');

  // Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
  server.engine('html', ngExpressEngine({
    bootstrap: AppServerModule,
  }));

  server.set('view engine', 'html');
  server.set('views', join(DIST_FOLDER, 'browser'));
  //server.set('views', distFolder);

  // Example Express Rest API endpoints
  // server.get('/api/**', (req, res) => { });
  // Serve static files from /browser
  server.get('*.*', express.static(distFolder, {
    maxAge: '1y'
  }));

  // All regular routes use the Universal engine
  server.get('*', (req, res) => {
    res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
  });

  return server;
}

function run(): void {
  const port = process.env.PORT || 4200;

  // Start up the Node server
  const server = app();
  server.listen(port, () => {
    console.log(`Node Express server listening on http://localhost:${port}`);
  });
}

// Webpack will replace 'require' with '__webpack_require__'
// '__non_webpack_require__' is a proxy to Node 'require'
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = mainModule && mainModule.filename || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
  run();
}

export * from './src/main.server';

angular.json

代码语言:javascript
复制
{
      "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
      "version": 1,
      "newProjectRoot": "projects",
      "projects": {
        "my-app-name": {
          "root": "",
          "sourceRoot": "src",
          "projectType": "application",
          "prefix": "app",
          "schematics": {
            "@schematics/angular:component": {
              "styleext": "scss"
            }
          },
          "architect": {
            "build": {
              "builder": "@angular-devkit/build-angular:browser",
              "options": {
                "outputPath": "dist/browser",
                "index": "src/index.html",
                "main": "src/main.ts",
                "polyfills": "src/polyfills.ts",
                "tsConfig": "src/tsconfig.app.json",
                "assets": [
                  "src/favicon.ico",
                  "src/assets"
                ],
                "styles": [
                  "src/assets/sass/main.scss",
                  "node_modules/bootstrap/scss/bootstrap.scss"
                ],
                "scripts": []
              },
              "configurations": {
                "production": {
                  "fileReplacements": [
                    {
                      "replace": "src/environments/environment.ts",
                      "with": "src/environments/environment.prod.ts"
                    }
                  ],
                  "optimization": true,
                  "outputHashing": "all",
                  "sourceMap": false,
                  "extractCss": true,
                  "namedChunks": false,
                  "aot": true,
                  "extractLicenses": true,
                  "vendorChunk": false,
                  "buildOptimizer": true
                }
              }
            },
            "serve": {
              "builder": "@angular-devkit/build-angular:dev-server",
              "options": {
                "browserTarget": "my-app-name:build",
                "sslKey": "ssl/server.key",
                "sslCert": "ssl/server.crt"
              },
              "configurations": {
                "production": {
                  "browserTarget": "my-app-name:build:production"
                }
              }
            },
            "server": {
              "builder": "@angular-devkit/build-angular:server",
              "options": {
                "outputPath": "dist/server",
                "main": "server.ts",
                "tsConfig": "src/tsconfig.server.json"
              },
              "configurations": {
                "production": {
                  "outputHashing": "media",
                  "fileReplacements": [
                    {
                      "replace": "src/environments/environment.ts",
                      "with": "src/environments/environment.prod.ts"
                    }
                  ],
                  "sourceMap": false,
                  "optimization": {
                    "scripts": false,
                    "styles": true
                  }
                }
              }
            },
            "serve-ssr": {
              "builder": "@nguniversal/builders:ssr-dev-server",
              "options": {
                "browserTarget": "my-app-name:build",
                "serverTarget": "my-app-name:server"
              },
              "configurations": {
                "production": {
                  "browserTarget": "my-app-name:build:production",
                  "serverTarget": "my-app-name:server:production"
                }
              }
            },
            "prerender": {
              "builder": "@nguniversal/builders:prerender",
              "options": {
                "browserTarget": "my-app-name:build:production",
                "serverTarget": "my-app-name:server:production",
                "routes": [
                  "/"
                ]
              },
              "configurations": {
                "production": {}
              }
            }
          }
        },
      },
      "defaultProject": "my-app-name"
    }

现在当我执行命令时

代码语言:javascript
复制
webpack:server

我犯了很多这样的错误:

未找到./src/app/components/auth/login/login.component.ts模块中的

错误:错误:无法解析'C:\Code\my-app-name\src\app\components\auth\login‘@ ./src/app/components/auth/login/login.component.ts 21:0-79 140:8-26 @ ./src/app/components/auth/login/login.module.ts中的“src/app/web-services/facebook-sdk.service”@ ./src/app/app-routing.module.ts @ ./src/app/app.module.ts @ ./src/app/app.server.module.ts @ ./src/main.server.ts @/server.ts

我不知道如何找出问题在哪里,它是否在我的配置中有坏的价值?

我查了几个小时,但找不到错误。

请帮帮我!

提前谢谢你

亚历克斯

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-11 13:13:50

我发现了问题:

在我的组件和模块中,我使用了带有相对路径的导入

代码语言:javascript
复制
import { ApiClientService } from 'src/app/web-services/api-client.service';

我把它改为绝对路径

代码语言:javascript
复制
import { ApiClientService } from '../../web-services/api-client.service';

现在建好了

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

https://stackoverflow.com/questions/64783842

复制
相关文章

相似问题

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