简体   繁体   English

Angular通用Webpack配置

[英]Angular universal webpack config

I'm trying to build server-side rendering on Ionic application. 我正在尝试在Ionic应用程序上构建服务器端渲染。 I've created everything from the manual: https://angular.io/guide/universal 我已经根据手册创建了所有内容: https : //angular.io/guide/universal

npm run build:ssr creates invalid dist/server.js file. npm run build:ssr创建无效的dist / server.js文件。 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" 该代码具有语法错误:“ SyntaxError:无效的正则表达式标志”

I think that there is something wrong with webpack.server.config.js. 我认为webpack.server.config.js出了点问题。 Maybe I must add some loader. 也许我必须添加一些加载程序。

Here is webpack.server.config.js code: 这是webpack.server.config.js代码:

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 ) 如何修复server.js文件中的错误(当我调用npm run build:ssrhttps://angular.io/guide/universal npm run build:ssr时)

my tsconfig.json: 我的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: 我已将此代码添加到angular.json架构师:

"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: 我已经将这些脚本添加到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: 我的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) npm run build:ssr(此命令在/ dist文件夹中创建许多文件。dist / server.js语法错误)

  2. npm run serve:ssr (This command failed with error: "SyntaxError: Invalid regular expression flags") npm run serve:ssr(此命令失败,错误:“ SyntaxError:无效的正则表达式标志”)

I think you need 3rd tsconfig.webpack-server.json . 我认为您需要第三个tsconfig.webpack-server.json For me there are 4: 对我来说有4个:

  • ./tsconfig.json - root tsconfig ./tsconfig.json根tsconfig
  • ./src/tsconfig.app.json - tsconfig used for building browser side bundle ./src/tsconfig.app.json用于构建浏览器端捆绑包的tsconfig
  • ./src/tsconfig.server.json - tsconfig used for building server side bundle ./src/tsconfig.server.json用于构建服务器端捆绑包的tsconfig
  • ./src/tsconfig.webpack-server.json - tsconfig used by webpack. ./src/tsconfig.webpack-server.json使用的tsconfig。

In webpack.server.config.js , need to specify the config manually: webpack.server.config.js ,需要手动指定配置:

    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. 在以上示例中,我使用tsconfig-paths-webpack-plugin

The reason for having multiple tsconfig's is because of target bundles are different. 具有多个tsconfig的原因是由于目标捆绑包不同。

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

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

Make sure that module and target are set accordingly. 确保相应地设置了moduletarget

For ./src/tsconfig.server.json : 对于./src/tsconfig.server.json

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

For ./src/tsconfig.app.json : 对于./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. 上面显示的只有moduletarget字段,因为它们似乎与您得到的错误有关,其他选项对于您的项目应该是必需的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM