universal: npm run serve:ssr : package.json does not exist

Bug Report

What is the expected behavior?

npm run build:ssr is building without errors. npm run serve:ssr is not running as expected

What is the current behavior?

npm run serve:ssr fails with the following errors

> x-y-z@0.0.0 serve:ssr /Users/NRMac/Projects/newSMT/xyz
> node dist/server

/Users/NRMac/Projects/newSMT/xyz/dist/server/main.js:173019
        throw new Error("package.json does not exist at " + package_json_path);
        ^

Error: package.json does not exist at /Users/NRMac/Projects/newSMT/xyz/dist/package.json
    at Object.PsoT.exports.find (/Users/NRMac/Projects/newSMT/xyz/dist/server/main.js:173019:15)
    at Object.wPNL (/Users/NRMac/Projects/newSMT/xyz/dist/server/main.js:308568:12)
    at __webpack_require__ (/Users/NRMac/Projects/newSMT/xyz/dist/server/main.js:20:30)
    at Object.XpdW (/Users/NRMac/Projects/newSMT/xyz/dist/server/main.js:196998:12)
    at __webpack_require__ (/Users/NRMac/Projects/newSMT/xyz/dist/server/main.js:20:30)
    at Object.g1pB (/Users/NRMac/Projects/newSMT/xyz/dist/server/main.js:229730:27)
    at __webpack_require__ (/Users/NRMac/Projects/newSMT/xyz/dist/server/main.js:20:30)
    at Object.Ou8q (/Users/NRMac/Projects/newSMT/xyz/dist/server/main.js:170377:14)
    at __webpack_require__ (/Users/NRMac/Projects/newSMT/xyz/dist/server/main.js:20:30)
    at Object.BYZf (/Users/NRMac/Projects/newSMT/xyz/dist/server/main.js:99702:12)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! set-my-test@0.0.0 serve:ssr: `node dist/server`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the set-my-test@0.0.0 serve:ssr script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/NRMac/.npm/_logs/2019-07-22T07_43_50_405Z-debug.log

What modules are related to this issue?

- [ ] aspnetcore-engine
- [ ] common
- [ ] express-engine
- [ ] hapi-engine
- [ ] module-map-ngfactory-loader

Minimal reproduction with instructions:

What is the use-case or motivation for changing an existing behavior?

Environment:

@nguniversal versions

  • express-engine:
  • module-map-ngfactory-loader:

Output from: ng --version.

Angular CLI: 8.1.2
Node: 10.16.0
OS: darwin x64
Angular: 8.1.2
... animations, cli, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... platform-server, router

Package                                    Version
--------------------------------------------------------------------
@angular-devkit/architect                  0.801.2
@angular-devkit/build-angular              0.801.2
@angular-devkit/build-optimizer            0.801.2
@angular-devkit/build-webpack              0.801.2
@angular-devkit/core                       8.1.2
@angular-devkit/schematics                 8.1.2
@angular/fire                              5.2.1
@ngtools/webpack                           8.1.2
@nguniversal/express-engine                8.1.1
@nguniversal/module-map-ngfactory-loader   8.1.1
@schematics/angular                        8.1.2
@schematics/update                         0.801.2
rxjs                                       6.5.2
typescript                                 3.4.5
webpack                                    4.35.2

Is there anything else we should know?

Working on Angular 8.1 with Firestore Tried modifying webpack.server.config.js, package.json and server.ts based on the issue here https://stackoverflow.com/questions/57030914/firebase-firestore-not-working-with-angular-universal-package-json-does-not-exi

webpack.server.config.js

// Work around for https://github.com/angular/angular-cli/issues/7200

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

const APP_NAME = "xyz"; // CHANGE ME

module.exports = {
  mode: "development",
  entry: {
    // This is our Express server for Dynamic universal
    server: "./server.ts"
  },
  resolve: { extensions: [".js", ".ts"] },
  externals: {
    "./dist/server/main": 'require("./server/main")'
    /* 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/
  },
  target: "node",
  optimization: {
    minimize: false
  },
  output: {
    // Puts the output at the root of the dist folder
    path: path.join(__dirname, `dist/${APP_NAME}`),
    library: "app",
    libraryTarget: "umd",
    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

/**
 * *** 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");

import { renderModuleFactory } from "@angular/platform-server";
import { REQUEST, RESPONSE } from "@nguniversal/express-engine/tokens";
import { ValueProvider } from "@angular/core";

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

const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), "dist");
const APP_NAME = "xyz"; // 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.engine("html", (_, options, callback) =>
  ngExpressEngine({
    bootstrap: AppServerModuleNgFactory,
    providers: [
      provideModuleMap(LAZY_MODULE_MAP),
      {
        provide: REQUEST,
        useValue: options.req
      },
      {
        provide: RESPONSE,
        useValue: options.req.res
      }
    ]
  })(_, options, callback)
);

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(DIST_FOLDER, {
    maxAge: "1y"
  })
);

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

// 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 });
});

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

Package.json

{
  "name": "x-of-y",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "compile:server": "webpack --config webpack.server.config.js --progress --colors",
    "serve:ssr": "node dist/server",
    "build:ssr": "npm run build:client-and-server-bundles && npm run compile:server",
    "build:client-and-server-bundles": "ng build --prod && ng run xyz:server:production --bundleDependencies all"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~8.1.2",
    "@angular/common": "~8.1.2",
    "@angular/compiler": "~8.1.2",
    "@angular/core": "~8.1.2",
    "@angular/forms": "~8.1.2",
    "@angular/platform-browser": "~8.1.2",
    "@angular/platform-browser-dynamic": "~8.1.2",
    "@angular/platform-server": "~8.1.2",
    "@angular/router": "~8.1.2",
    "@nguniversal/express-engine": "^8.1.1",
    "@nguniversal/module-map-ngfactory-loader": "8.1.1",
    "animate.css": "^3.7.2",
    "core-js": "^2.5.4",
    "express": "^4.15.2",
    "rxjs": "~6.5.2",
    "tslib": "^1.9.0",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.801.2",
    "@angular/cli": "~8.1.2",
    "@angular/compiler-cli": "~8.1.2",
    "@angular/fire": "^5.2.1",
    "@angular/language-service": "~8.1.2",
    "@fortawesome/fontawesome-free": "^5.9.0",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "chart.js": "^2.8.0",
    "codelyzer": "^5.0.1",
    "easy-pie-chart": "^2.1.7",
    "firebase": "^6.3.0",
    "hammerjs": "^2.0.8",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "ngx-quill": "^7.1.0",
    "protractor": "~5.4.0",
    "quill": "^1.3.6",
    "quill-emoji": "^0.1.7",
    "screenfull": "^4.2.0",
    "tinify": "^1.6.0-beta.2",
    "ts-loader": "^5.2.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "~3.4.5",
    "webpack-cli": "^3.1.0"
  }
}

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 16
  • Comments: 42 (5 by maintainers)

Most upvoted comments

@Gbuomprisco, thanks for the reproduction. I was able to look at it. To resolve the package.json does not exist error. You’d need to add grpc as externalDependencies.

Ex:

        "server": {
          "builder": "@angular-devkit/build-angular:server",
          "options": {
            "outputPath": "dist/ng-ssr-fire/server",
            "main": "server.ts",
            "tsConfig": "tsconfig.server.json",
            "externalDependencies": [
              "grpc"
            ]
          },
          "configurations": {
            "production": {
              "outputHashing": "media",
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "sourceMap": false,
              "optimization": true
            }
          }
        },

We have multiple people using angular fire who seem to have problem with --bundleDependencies all. The current workaround is to just remove/set --bundleDependencies none.

We are going to follow up with angularfire folks to fix this properly

"@grpc/proto-loader"

this does resolve the build error. but when the function executes, it gives a runtime error

ERROR Error: ENOENT: no such file or directory, open '/Users/ritikrishu/Documents/Personal/gumnam-blog/functions/dist/gumnam-blog/server/src/protos/google/firestore/v1/firestore.proto'
>      at Object.openSync (fs.js:440:3)
>      at Object.readFileSync (fs.js:342:35)
>      at fetch (/Users/ritikrishu/Documents/Personal/gumnam-blog/functions/node_modules/protobufjs/src/root.js:160:34)
>      at Root.load (/Users/ritikrishu/Documents/Personal/gumnam-blog/functions/node_modules/protobufjs/src/root.js:194:13)
>      at Root.loadSync (/Users/ritikrishu/Documents/Personal/gumnam-blog/functions/node_modules/protobufjs/src/root.js:235:17)
>      at Object.loadSync (/Users/ritikrishu/Documents/Personal/gumnam-blog/functions/node_modules/@grpc/proto-loader/build/src/index.js:221:27)
>      at loadProtos (/Users/ritikrishu/Documents/Personal/gumnam-blog/functions/dist/gumnam-blog/server/main.js:1:1597303)
>      at NodePlatform.loadConnection (/Users/ritikrishu/Documents/Personal/gumnam-blog/functions/dist/gumnam-blog/server/main.js:1:1597460)
>      at FirestoreClient.initializeRest (/Users/ritikrishu/Documents/Personal/gumnam-blog/functions/dist/gumnam-blog/server/main.js:1:1508557)
>      at /Users/ritikrishu/Documents/Personal/gumnam-blog/functions/dist/gumnam-blog/server/main.js:1:1505438 {

angular version 9^

@Gbuomprisco the ɵngcc0.ɵɵdefineInjectable is not a function error is related to https://github.com/angular/angular/issues/34653

For the other error try adding the below:

"externalDependencies": [
  "grpc",
  "@grpc/proto-loader"
]

This sounds like a work around rather than a solution. Isn’t --bundleDependencies all there for a reason?

If you can, you could create a separate module for Browser, and import AngularFire modules there.

For example, create a app.browser.module.ts - and add all your AngularFire imports there.

Then just point your main.ts file to bootstrap from that module instead.

Has anyone solved this issue yet? @kpsrinivas @vikerman @bdairy @anuragd7

The problem is “build:client-and-server-bundles”: “ng build --prod && ng run your-project:server:production --bundleDependencies all” in package.json . When you change it to ng run your-project:server:production --bundleDependencies none it works. But if you try to package it, the externals are getting messed up.

Added reproduction here: https://github.com/Gbuomprisco/ng-ssr-fire

If I use bundleDependencies false, I get the following error:

Error: No NgModule metadata found for 'AppServerModule'.
    at NgModuleResolver.resolve (/Users/giancarlo/Lab/ng-ssr-fire/node_modules/@angular/compiler/bundles/compiler.umd.js:22899:27)
    at CompileMetadataResolver.getNgModuleMetadata (/Users/giancarlo/Lab/ng-ssr-fire/node_modules/@angular/compiler/bundles/compiler.umd.js:22002:47)
    at JitCompiler._loadModules (/Users/giancarlo/Lab/ng-ssr-fire/node_modules/@angular/compiler/bundles/compiler.umd.js:28191:55)
    at JitCompiler._compileModuleAndComponents (/Users/giancarlo/Lab/ng-ssr-fire/node_modules/@angular/compiler/bundles/compiler.umd.js:28172:40)
    at JitCompiler.compileModuleAsync (/Users/giancarlo/Lab/ng-ssr-fire/node_modules/@angular/compiler/bundles/compiler.umd.js:28132:41)
    at CompilerImpl.compileModuleAsync (/Users/giancarlo/Lab/ng-ssr-fire/node_modules/@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js:339:35)
    at CommonEngine.<anonymous> (/Users/giancarlo/Lab/ng-ssr-fire/node_modules/@nguniversal/express-engine/bundles/express-engine.umd.js:95:69)
    at step (/Users/giancarlo/Lab/ng-ssr-fire/node_modules/tslib/tslib.js:136:27)
    at Object.next (/Users/giancarlo/Lab/ng-ssr-fire/node_modules/tslib/tslib.js:117:57)
    at /Users/giancarlo/Lab/ng-ssr-fire/node_modules/tslib/tslib.js:110:75

If I don’t set bundleDependencies to false, I get this error:


/Users/giancarlo/Lab/ng-ssr-fire/dist/ng-ssr-fire/server/main.js:1
!function(e,a){for(var i in a)e[i]=a[i]}(exports,function(modules){var installedModules={};function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module=installedModules[moduleId]={i:moduleId,l:!1,exports:{}};return modules[moduleId].call(module.exports,module,module.exports,__webpack_require__),module.l=!0,module.exports}return __webpack_require__.m=modules,__webpack_require__.c=installedModules,__webpack_require__.d=function(exports,name,getter){__webpack_require__.o(exports,name)||Object.defineProperty(exports,name,{enumerable:!0,get:getter})},__webpack_require__.r=function(exports){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(exports,"__esModule",{value:!0})},__webpack_require__.t=function(value,mode){if(1&mode&&(value=__webpack_require__(value)),8&mode)return value;if(4&mode&&"object"==t

Error: package.json does not exist at /Users/giancarlo/Lab/ng-ssr-fire/dist/ng-ssr-fire/package.json
    at Object.PsoT.exports.find (/Users/giancarlo/Lab/ng-ssr-fire/dist/ng-ssr-fire/server/main.js:1:1976398)
    at Object.wPNL (/Users/giancarlo/Lab/ng-ssr-fire/dist/ng-ssr-fire/server/main.js:1:3479745)
    at __webpack_require__ (/Users/giancarlo/Lab/ng-ssr-fire/dist/ng-ssr-fire/server/main.js:1:295)
    at Object.XpdW (/Users/giancarlo/Lab/ng-ssr-fire/dist/ng-ssr-fire/server/main.js:1:2178193)
    at __webpack_require__ (/Users/giancarlo/Lab/ng-ssr-fire/dist/ng-ssr-fire/server/main.js:1:295)
    at Object.g1pB (/Users/giancarlo/Lab/ng-ssr-fire/dist/ng-ssr-fire/server/main.js:1:2904722)
    at __webpack_require__ (/Users/giancarlo/Lab/ng-ssr-fire/dist/ng-ssr-fire/server/main.js:1:295)
    at Object.Ou8q (/Users/giancarlo/Lab/ng-ssr-fire/dist/ng-ssr-fire/server/main.js:1:1935573)
    at __webpack_require__ (/Users/giancarlo/Lab/ng-ssr-fire/dist/ng-ssr-fire/server/main.js:1:295)
    at Object.BYZf (/Users/giancarlo/Lab/ng-ssr-fire/dist/ng-ssr-fire/server/main.js:1:1279835)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! ng-ssr-fire@0.0.0 serve:ssr: `node dist/ng-ssr-fire/server/main.js`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the ng-ssr-fire@0.0.0 serve:ssr script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/giancarlo/.npm/_logs/2020-01-03T18_01_46_267Z-debug.log

I also tried running $ ngcc --properties es2015 browser module main --create-ivy-entry-points --first-only and $ ngcc --properties es2015 browser module main --create-ivy-entry-points

It’s weird I am not getting the same error. I’ll try more configurations.

add this @firebase/firestore to externalDependencies

// angular.json
// projects.web.architect
...
 "server": {
          "builder": "@angular-devkit/build-angular:server",
          "options": {
            ...
            "externalDependencies": [
              "@firebase/firestore"
            ]
            ...
          }

I already create an PR to clarify that https://github.com/angular/angularfire/pull/2372/files?short_path=e76f33d#diff-e76f33db0439ee8e320dfa7ecf47f09b

@kuncevic yeah, I got the same error for using angularfire. current workaround is by setting grpc as externalDependencies as @alan-agius4 said.

I fixed error “Element is not defined” deleting “ng-inline-svg”: “^8.5.1”, in package.json, Angular 9

@codemysoul there is no point of SSR, if you only include those in the browser bundle.

Has anyone solved this issue yet? @kpsrinivas @vikerman @bdairy @anuragd7 Looks like Vikerman’s response is the best fix and seems to work.

  1. Go to your package.json file, under the “scripts” section & look for “build:client-and-server-bundles”.
  2. At the end of that line it has “–bundleDependencies all”
  3. set that to “–bundleDependencies none” or delete it(I set it to all and it works)
  4. re-run npm run build:ssr

This worked with Angular 8, but with not with Angular 9 (see below)

We have multiple people using angular fire who seem to have problem with --bundleDependencies all. The current workaround is to just remove/set --bundleDependencies none.

We are going to follow up with angularfire folks to fix this properly

Is this supposed to work with Angular 9? The workaround used to work - but now the component’s template and styles won’t get bundled anymore