【问题标题】:Firebase firestore not working with Angular Universal: package.json does not existFirebase firestore 不适用于 Angular Universal:package.json 不存在
【发布时间】:2019-11-23 15:14:29
【问题描述】:

我按照this 教程创建了服务器端呈现的应用程序。之后我运行 npm install firebase @angular/fire --save 并像这样在 AppModule 中导入模块

import { AngularFireModule } from "@angular/fire";
import { AngularFirestoreModule } from "@angular/fire/firestore";
import { AngularFireStorageModule } from "@angular/fire/storage";

 AngularFireModule.initializeApp(environment.firebase),
 AngularFirestoreModule,
 AngularFireStorageModule,

当我尝试使用 npm run build:ssr && npm run serve:ssr 为应用程序提供服务时发生错误。 我得到的错误是

C:\Users\user\Documents\prueba\PruebaApp\dist\server\main.js:159431
        throw new Error("package.json does not exist at " + package_json_path);
        ^
Error: package.json does not exist at C:\Users\user\Documents\prueba\PruebaApp\dist\package.json
    at Object.PsoT.exports.find (C:\Users\user\Documents\prueba\PruebaApp\dist\server\main.js:159431:15)
    at Object.wPNL (C:\Users\user\Documents\prueba\PruebaApp\dist\server\main.js:188373:12)
    at __webpack_require__ (C:\Users\user\Documents\prueba\PruebaApp\dist\server\main.js:20:30)
    at Object.XpdW (C:\Users\user\Documents\prueba\PruebaApp\dist\server\main.js:166719:12)
    at __webpack_require__ (C:\Users\user\Documents\prueba\PruebaApp\dist\server\main.js:20:30)
    at Object.g1pB (C:\Users\user\Documents\prueba\PruebaApp\dist\server\main.js:175163:27)
    at __webpack_require__ (C:\Users\user\Documents\prueba\PruebaApp\dist\server\main.js:20:30)
    at Object.Ou8q (C:\Users\user\Documents\prueba\PruebaApp\dist\server\main.js:156910:14)
    at __webpack_require__ (C:\Users\user\Documents\prueba\PruebaApp\dist\server\main.js:20:30)
    at Object.BYZf (C:\Users\user\Documents\prueba\PruebaApp\dist\server\main.js:21357:12)

如果我删除 AngularFirestoreModule 项目构建并正常工作。

我正在使用 Angular 8.1.1、firebase 6.3.0 和 angular/fire 5.2.1

【问题讨论】:

  • 我有完全相同的问题,我也隔离了 AngularFirestoreModule 正在制造问题。还没有解决方案。

标签: angular firebase google-cloud-firestore angularfire2 angular-universal


【解决方案1】:

如果您想从 firebase 函数中进行 ssr 项目,这就是解决方案。

正确的答案是您需要使用--bundleDependencies none 构建您的服务器包,或者只删除--bundleDependencies all

正确的行:package.json

    "build:client-and-server-bundles": "ng build --prod && ng run Medical-Practice:server:production --bundleDependencies none"

之后,如果您想将 ssr 上传到 ./functions/package.json 中所需的函数,包括来自主 Angular 项目 ./package.json 的所有依赖项

示例:./functions/package.json

    "@angular/animations": "~8.2.0",
    "@angular/common": "~8.2.0",
    "@angular/compiler": "~8.2.0",
    "@angular/core": "~8.2.0",
    "@angular/fire": "^5.2.1",
    "@angular/forms": "~8.2.0",
    "@angular/platform-browser": "~8.2.0",
    "@angular/platform-browser-dynamic": "~8.2.0",
    "@angular/platform-server": "~8.2.0",
    "@angular/router": "~8.2.0",
    "@nguniversal/express-engine": "^8.1.1",
    "@nguniversal/module-map-ngfactory-loader": "8.1.1",
    "express": "^4.15.2",
    "firebase": "^6.3.4",
    "rxjs": "~6.4.0",
    "tslib": "^1.10.0",
    "zone.js": "~0.9.1"

正如我们所知,当依赖项捆绑在捆绑文件中时,firebase 不希望在 SSR 上工作。上层解决方案有效,因为将 package.json 文件部署到 firebase 函数,并且在部署函数服务器后运行 npm install 命令,因此在常规服务器上会有一些不同的解决方案。

例如,如果您想将带有 firebase 的 angular ssr 上传到 App Engine,我不确定,但部署后它会运行 npm run start 并且应用程序启动,因此您需要将:"start": "npm run serve:ssr" 行更改为:"start": "npm install && npm run serve:ssr"。并且不要忘记将 package.json 与应用程序一起上传。

重要

以防万一我没有在 App Engine 上检查,但这可能是解决方案。

【讨论】:

  • 嗨。我像你说的那样删除了命令“bundleDependencies all”,现在我没有收到任何错误,但是当我尝试使用“npm run build:ssr && npm run serve:ssr”渲染应用程序时,如果我去 localhost:4000 它一直加载很长时间,直到它返回一个空白页面,并显示“此页面不起作用”的错误。
  • 它只是 firebase 功能的解决方案。至少我只是在那里尝试它并且它有效。
  • 这对我有用,但不知何故主页无法转换为 SSR。
  • 您需要重命名 index.html 文件。这是因为所有浏览器请求https://some-page.com/ 都等于https://some-page.com/index.html。在文件 firebase.json "rewrites": [ { "source": "**", "function": "ssr" } ] 中,如果请求不适合但您有文件 index.html 所以请求适合,则会触发函数。
【解决方案2】:

这里有同样的错误,查看我找到本指南的 angularfire 文档:

https://github.com/angular/angularfire2/blob/master/docs/universal/getting-started.md

它无法正常工作,所以我找到了一个解决方案,将构建过程更改为:

webpack.server.config.js

const path = require('path');
const webpack = require('webpack');

const APP_NAME = 'YOUR APP NAME HERE'; // CHANGE ME

module.exports = {
  entry: {  server: './server.ts' },
  resolve: { extensions: ['.js', '.ts'] },
  mode: 'development',
  target: 'node',
  externals: [
    /* Firebase has some troubles being webpacked when in
       in the Node environment, let's skip it.
       Note: you may need to exclude other dependencies depending
       on your project. */
    /^firebase/
  ],
  output: {
    // Export a UMD of the webpacked server.ts & deps, for
    // rendering in Cloud Functions
    path: path.join(__dirname, `dist/${APP_NAME}`),
    library: 'app',
    libraryTarget: 'umd',
    filename: '[name].js'
  },
  module: {
    rules: [
      { test: /\.ts$/, loader: 'ts-loader' }
    ]
  },
  plugins: [
    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'),
      {}
    )
  ]
}

server.ts

/**
 * *** NOTE ON IMPORTING FROM ANGULAR AND NGUNIVERSAL IN THIS FILE ***
 *
 * If your application uses third-party dependencies, you'll need to
 * either use Webpack or the Angular CLI's `bundleDependencies` feature
 * in order to adequately package them for use on the server without a
 * node_modules directory.
 *
 * However, due to the nature of the CLI's `bundleDependencies`, importing
 * Angular in this file will create a different instance of Angular than
 * the version in the compiled application code. This leads to unavoidable
 * conflicts. Therefore, please do not explicitly import from @angular or
 * @nguniversal in this file. You can export any needed resources
 * from your application's main.server.ts file, as seen below with the
 * import for `ngExpressEngine`.
 */

import 'zone.js/dist/zone-node';
import 'reflect-metadata';

import { enableProdMode } from '@angular/core';

import * as express from 'express';
import {join} from 'path';
import { readFileSync } from 'fs';

// Polyfills required for Firebase
(global as any).WebSocket = require('ws');
(global as any).XMLHttpRequest = require('xhr2');

enableProdMode();
// Express server
const app = express();

const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), 'dist');
const APP_NAME = 'YOUR APP NAME HERE'; // CHANGE ME

// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const {AppServerModuleNgFactory, LAZY_MODULE_MAP, ngExpressEngine, provideModuleMap} = require(`./dist/server/main`);

//index.html template
const template = readFileSync(join(DIST_FOLDER, 'browser', 'index.html')).toString();

// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
app.engine('html', ngExpressEngine({
  bootstrap: AppServerModuleNgFactory,
  providers: [
    provideModuleMap(LAZY_MODULE_MAP)
  ]
}));

app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));

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

// All regular routes use the Universal engine
app.get('*', (req, res) => {
  res.render(join(DIST_FOLDER, 'browser', 'index.html'), { req });
});

// If we're not in the Cloud Functions environment, spin up a Node server
if (!process.env.FUNCTION_NAME) {
  app.listen(PORT, () => {
    console.log(`Node server listening on http://localhost:${PORT}`);
  });
}

package.json

    "build": "ng build && npm run build:ssr",
    "build:ssr": "ng run cuervo-app:server && npm run webpack:ssr",
    "webpack:ssr": "webpack --config webpack.server.config.js",
    "serve:ssr": "node dist/cuervo-app/server.js"

小心你应用的引用变量!

希望对你也有帮助!很难找到这个解决方案,我不知道它是否是最好的,但是官方文档没有用。

再见!

【讨论】:

  • 非常好,我会试试你的解决方案,然后回复你信息。非常感谢。
  • 嗨。我尝试了您的解决方案,它让我可以构建和部署应用程序,但它破坏了组件中元服务的使用。现在,当我更改 og:image 或 og:title 之类的元标记时,它不会更新。我已经重建了应用程序并清理了缓存,但我没有更新。我该如何解决这个问题?
  • 我对构建 Angular 应用程序所需的命令也有一些疑问。我不确定我必须运行哪些命令才能让应用准备好部署(我使用 GCP)
  • 这个在 github 上讨论的评论为我解决了这个问题:github.com/angular/universal/issues/1207#issuecomment-516525087
  • 嗨。我尝试更改命令,例如删除“--bundleDependencies all”,但是当我尝试使用 npm run build:ssr && npm run serve:ssr 渲染应用程序时,如果我转到 localhost:4000 它会持续加载很长时间直到它返回一个空白页面,并显示“此页面不起作用”的错误。
猜你喜欢
  • 2019-12-19
  • 2022-01-06
  • 1970-01-01
  • 2020-03-26
  • 2020-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多