Firebase Firestore无法与Angular Universal配合使用:package.json不存在

时间:2019-07-14 20:27:56

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

我遵循了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,则项目将构建并正常工作。

Im使用Angular 8.1.1,firebase 6.3.0和angular / fire 5.2.1

2 个答案:

答案 0 :(得分: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"

请注意您应用的参考变量!

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

再见!

答案 1 :(得分:2)

如果要从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中所需的功能,请包括来自主要角度项目./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的角度ssr上传到App Engine,但我不确定在部署后它会运行npm run start并启动应用程序,因此您需要将"start": "npm run serve:ssr"行更改为:{ {1}}。并且不要忘记将package.json与应用程序一起上传。

重要

  
    

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