1
votes

I'm trying to build server-side rendering on Ionic application. I've created everything from the manual: https://angular.io/guide/universal

npm run build:ssr creates invalid dist/server.js file. Here is the invalid code from the file:

if(typeof !!/Users/myuser/www/myapp/node_modules/file-loader/dist/cjs.js?name=[name].[ext]&outputPath=svg!./ios-add-circle-outline.svg === 'undefined') {
   // ...
}

This code has syntax error: "SyntaxError: Invalid regular expression flags"

I think that there is something wrong with webpack.server.config.js. Maybe I must add some loader.

Here is webpack.server.config.js code:

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

module.exports = {
  entry: { server: "./server.ts" },
  resolve: { extensions: [".js", ".ts"] },
  target: "node",
  mode: "none",
  // this makes sure we include node_modules and other 3rd party libraries
  externals: [/node_modules/],
  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"),
      {}
    )
  ]
};

How to fix this error in server.js file (when I call npm run build:ssr from https://angular.io/guide/universal)

my tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "types" : ["node"],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}

I've added this code to angular.json architect:

"server": {
  "builder": "@angular-devkit/build-angular:server",
  "options": {
    "outputPath": "dist/server",
    "main": "src/main.server.ts",
    "tsConfig": "src/tsconfig.server.json"
  }
}

I've added these scripts to package.json:

"build:ssr": "npm run build:client-and-server-bundles && npm run webpack:server",
"serve:ssr": "node dist/server.js",
"build:client-and-server-bundles": "ng build --prod && ng run app:server",
"webpack:server": "webpack --config webpack.server.config.js --progress --colors",

my tsconfig.server.json:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "baseUrl": "./",
    "module": "commonjs"
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ],
  "angularCompilerOptions": {
    "entryModule": "app/app.server.module#AppServerModule"
  }
}

my 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');

// 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('index', { req });
});

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

Steps to reproduce error:

  1. npm run build:ssr (This command creates many files in /dist folder. dist/server.js has syntax error)

  2. npm run serve:ssr (This command failed with error: "SyntaxError: Invalid regular expression flags")

1
I think you should show your minimal error reproducing server.ts. And tsconfig. And section from your angular-cli.json you added for ssr.muradm
ok, I've updated questionIldar
what about src/tsconfig.server.json? and server.ts itself?muradm

1 Answers

0
votes

I think you need 3rd tsconfig.webpack-server.json. For me there are 4:

  • ./tsconfig.json - root tsconfig
  • ./src/tsconfig.app.json - tsconfig used for building browser side bundle
  • ./src/tsconfig.server.json - tsconfig used for building server side bundle
  • ./src/tsconfig.webpack-server.json - tsconfig used by webpack.

In webpack.server.config.js, need to specify the config manually:

    plugins: [
      new TsconfigPathsPlugin({ configFile: './src/tsconfig.webpack-server.json', logLevel: 'INFO', silent: false, logInfoToStdOut: true }),
    ],

I use tsconfig-paths-webpack-plugin in the above example.

The reason for having multiple tsconfig's is because of target bundles are different.

For ./src/tsconfig.webpack-server.json:

"compilerOptions": {
  "module": "commonjs",
  "target": "es2017",
}

Make sure that module and target are set accordingly.

For ./src/tsconfig.server.json:

"compilerOptions": {
  "module": "commonjs",
  "target": "es5",
}

For ./src/tsconfig.app.json:

"compilerOptions": {
  "module": "es2015",
  "target": "es5",
}

Only module and target fields illustrated above as they are seems to be relevant to the error you getting, other options should be as necessary for your project.