【问题标题】:No NgModule metadata found for 'AppModule' Error in Angular 5 server-side rendering with --env.prod使用 --env.prod 在 Angular 5 服务器端渲染中找不到“AppModule”错误的 NgModule 元数据
【发布时间】:2018-05-03 05:04:34
【问题描述】:

我正在尝试将 ASP.NET Core + Angular 4 SPA 项目从 .NET Core 2.0.0/Angular4 升级到 .NET Core 2.0.3/Angular5。除了生产环境中的服务器端渲染外,我设法让一切正常工作,即当我发布应用程序时:

发生未处理的异常:未找到“AppModule”的 NgModule 元数据。
错误:找不到“AppModule”的 NgModule 元数据。

只有同时满足这两个条件时才会出现问题:

  • Webpack 使用 --env.prod 开关构建包
  • Index.cshtml 视图文件包含asp-prerender-module 参数,如下例所示:

    <app asp-prerender-module="ClientApp/dist/main-server">Loading...</app>

如果我移除开关和/或参数,问题就会消失(连同 SSR)。

我可以提供很多其他信息:

  • 这与 IIS 无关,它发生在 Kestrel 级别。
  • 它与 Web 服务器计算机无关,因为我什至可以通过在 DebugRelease 运行之前手动启动 Webpack 并使用 --end.prod 开关在本地复制它.
  • 它似乎与源代码没有任何关系,因为即使使用带有非常基本的 AppModule 文件和琐碎代码的单组件示例应用程序,我也可以重现它。
  • 该项目在 .NET Core 2.0.0 和 Angular 4.3.x 上运行良好。
  • 我在webpack.config.js 文件中更改的唯一主要内容是将AotPlugin 替换为Angular5-specific@ngtools/webpack 包提供的新AngularCompilerPlugin:我认为这也可能是原因,因为--env.prod 开关使用该 AOT 编译器而不是 JIT 编译器。那,或者与.NET SpaServices package 相关的东西——可能与新的 Angular5 和/或新的 AoT 编译器不相称?

遗憾的是,我无法恢复到以前的 AotPlugin,因为它也会引发错误 - 这是完全可以理解的,因为它不适合与 Angular5 一起使用。

软件版本

  • .NET Core 2.0.3
  • Angular 5.0.2
  • @ngtools/webpack 1.8.2(也尝试了 1.8.1 - 结果相同)
  • WebPack 2.6.1(也尝试使用 2.5.6 - 结果相同)

webpack.config.js

const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AotPlugin = require('@ngtools/webpack').AngularCompilerPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;

module.exports = (env) => {
    // Configuration in common to both client-side and server-side bundles
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: { modules: false },
        context: __dirname,
        resolve: { extensions: [ '.js', '.ts' ] },
        output: {
            filename: '[name].js',
            publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        module: {
            rules: [
                { test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/, include: /ClientApp/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] : '@ngtools/webpack' },
                { test: /\.html$/, use: 'html-loader?minimize=false' },
                { test: /\.css$/, use: [ 'to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] },
                { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
            ]
        },
        plugins: [new CheckerPlugin()]
    };

    // Configuration for client-side bundle suitable for running in browsers
    const clientBundleOutputDir = './wwwroot/dist';
    const clientBundleConfig = merge(sharedConfig, {
        entry: { 'main-client': './ClientApp/boot.browser.ts' },
        output: { path: path.join(__dirname, clientBundleOutputDir) },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./wwwroot/dist/vendor-manifest.json')
            })
        ].concat(isDevBuild ? [
            // Plugins that apply in development builds only
            new webpack.SourceMapDevToolPlugin({
                filename: '[file].map', // Remove this line if you prefer inline source maps
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
            })
        ] : [
            // Plugins that apply in production builds only
            new webpack.optimize.UglifyJsPlugin(),
            new AotPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.module.browser#AppModule'),
                exclude: ['./**/*.server.ts']
            })
        ])
    });

    // Configuration for server-side (prerendering) bundle suitable for running in Node
    const serverBundleConfig = merge(sharedConfig, {
        resolve: { mainFields: ['main'] },
        entry: { 'main-server': './ClientApp/boot.server.ts' },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./ClientApp/dist/vendor-manifest.json'),
                sourceType: 'commonjs2',
                name: './vendor'
            })
        ].concat(isDevBuild ? [] : [
            // Plugins that apply in production builds only
            new AotPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.module.server#AppModule'),
                exclude: ['./**/*.browser.ts']
            })
        ]),
        output: {
            libraryTarget: 'commonjs',
            path: path.join(__dirname, './ClientApp/dist')
        },
        target: 'node',
        devtool: 'inline-source-map'
    });

    return [clientBundleConfig, serverBundleConfig];
};

【问题讨论】:

  • 你能分享你的 webpack.config.js 文件吗? TIA
  • @GeekHour 刚刚做了:谢谢。

标签: asp.net angular asp.net-core


【解决方案1】:

Angular 5 的 @ngtool/webpack configuration 与 Angular 2/4 略有不同。因此,我将webpack.config.js 更改如下,

const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AngularCompilerPlugin = require('@ngtools/webpack').AngularCompilerPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;

module.exports = (env) => {
    // Configuration in common to both client-side and server-side bundles
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: { modules: false },
        context: __dirname,
        resolve: { extensions: [ '.js', '.ts' ] },
        output: {
            filename: '[name].js',
            publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        module: {
            rules: [
                { test: /\.ts$/, include: /ClientApp/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] : '@ngtools/webpack' },
                { test: /\.html$/, use: 'html-loader?minimize=false' },
                { test: /\.css$/, use: [ 'to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] },
                { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' },
                {
                    test: /(?:\.ngfactory\.js|\.ngstyle\.js)$/,
                    loader: '@ngtools/webpack',
                    options: {
                        tsConfigPath: '/tsconfig.json',
                    }
                }
            ]
        },
        plugins: [new CheckerPlugin()]
    };

    // Configuration for client-side bundle suitable for running in browsers
    const clientBundleOutputDir = './wwwroot/dist';
    const clientBundleConfig = merge(sharedConfig, {
        entry: { 'main-client': './ClientApp/boot.browser.ts' },
        output: { path: path.join(__dirname, clientBundleOutputDir) },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./wwwroot/dist/vendor-manifest.json')
            })
        ].concat(isDevBuild ? [
            // Plugins that apply in development builds only
            new webpack.SourceMapDevToolPlugin({
                filename: '[file].map', // Remove this line if you prefer inline source maps
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
            })
        ] : [
            // Plugins that apply in production builds only
                new webpack.optimize.UglifyJsPlugin(),
                new AngularCompilerPlugin({
                    tsConfigPath: './tsconfig.json',
                    entryModule: path.join(__dirname, 'ClientApp/app/app.module.browser#AppModule'),
                    exclude: ['./**/*.server.ts']
                })
        ])
    });

    // Configuration for server-side (prerendering) bundle suitable for running in Node
    const serverBundleConfig = merge(sharedConfig, {
        resolve: { mainFields: ['main'] },
        entry: { 'main-server': './ClientApp/boot.server.ts' },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./ClientApp/dist/vendor-manifest.json'),
                sourceType: 'commonjs2',
                name: './vendor'
            })
        ].concat(isDevBuild ? [] : [
            // Plugins that apply in production builds only
            new AngularCompilerPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.module.server#AppModule'),
                exclude: ['./**/*.browser.ts']
            })
        ]),
        output: {
            libraryTarget: 'commonjs',
            path: path.join(__dirname, './ClientApp/dist')
        },
        target: 'node',
        devtool: 'inline-source-map'
    });

    return [clientBundleConfig, serverBundleConfig];
};

这是我的package.json 文件,

   {
  "dependencies": {
    "@angular/animations": "^5.0.2",
    "@angular/cdk": "^5.0.0-rc0",
    "@angular/cli": "^1.6.0-beta.2",
    "@angular/common": "^5.0.2",
    "@angular/compiler": "^5.0.2",
    "@angular/compiler-cli": "^5.0.2",
    "@angular/core": "^5.0.2",
    "@angular/forms": "^5.0.2",
    "@angular/http": "^5.0.2",
    "@angular/material": "^5.0.0-rc0",
    "@angular/platform-browser": "^5.0.2",
    "@angular/platform-browser-dynamic": "^5.0.2",
    "@angular/platform-server": "^5.0.2",
    "@angular/router": "^5.0.2",
    "@ngtools/webpack": "^1.8.3",
    "@types/webpack-env": "^1.13.2",
    "angular2-template-loader": "0.6.2",
    "aspnet-prerendering": "^3.0.1",
    "aspnet-webpack": "^2.0.1",
    "awesome-typescript-loader": "^3.4.0",
    "bootstrap": "3.3.7",
    "css": "2.2.1",
    "css-loader": "^0.28.7",
    "es6-shim": "0.35.3",
    "event-source-polyfill": "0.0.12",
    "expose-loader": "0.7.4",
    "extract-text-webpack-plugin": "^3.0.2",
    "file-loader": "^1.1.5",
    "html-loader": "^0.5.1",
    "isomorphic-fetch": "2.2.1",
    "jquery": "3.2.1",
    "json-loader": "^0.5.7",
    "preboot": "^5.1.7",
    "raw-loader": "0.5.1",
    "reflect-metadata": "0.1.10",
    "request": "^2.83.0",
    "rxjs": "^5.5.2",
    "style-loader": "^0.19.0",
    "to-string-loader": "1.1.5",
    "typescript": "^2.6.1",
    "url-loader": "^0.6.2",
    "webpack": "^3.8.1",
    "webpack-hot-middleware": "^2.20.0",
    "webpack-merge": "^4.1.1",
    "zone.js": "^0.8.18"
  },
  "devDependencies": {
    "@types/chai": "^4.0.5",
    "@types/jasmine": "^2.8.2",
    "@types/node": "^8.0.53",
    "chai": "^4.1.2",
    "jasmine-core": "2.8.0",
    "karma": "1.7.1",
    "karma-chai": "0.1.0",
    "karma-chrome-launcher": "2.2.0",
    "karma-cli": "1.0.1",
    "karma-jasmine": "1.1.0",
    "karma-webpack": "2.0.6"
  },
  "name": "aspnetcoreangularspa",
  "private": true,
  "scripts": {
    "test": "karma start ClientApp/test/karma.conf.js"
  },
  "version": "0.0.0"
}

如果您在运行该解决方案时仍然遇到问题,请查看此repository 以获得有效的解决方案。

希望对你有帮助:)

【讨论】:

  • 我用你的 package.json / webpack.config.json (+vendor) / tsconfig.json 试过了:很遗憾,问题仍然存在。
  • 在您的项目中禁用 SSR。在启用SSR 时,当前项目配置将无法进行 treeshaking。他们正在开发一个新模板以使其正常工作。看看团队成员的评论-github.com/aspnet/JavaScriptServices/issues/…
  • 不错的收获!看来我说 SpaServices 与 Angular 5 不相称是对的……我想我会一直禁用它,直到他们弄清楚如何支持它。
  • 是的..这个问题暂时没有明确的答案:)
  • 你应该得到你的赏金 :)
【解决方案2】:

我在搜索此处描述的问题的解决方案时发现了您的问题: https://github.com/aspnet/JavaScriptServices/issues/1388 所以我尝试了您的 webpack-config 并尝试从存储库运行应用程序,但是当我执行“dotnet publish”然后运行应用程序时,我收到此错误:

Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]
      An unhandled exception has occurred: No NgModule metadata found for 'AppModule'.
      Error: No NgModule metadata found for 'AppModule'.
    at NgModuleResolver.module.exports.NgModuleResolver.resolve

【讨论】:

  • 我们在同一条船上。我现在试试赏金,让我们看看会发生什么:)
【解决方案3】:

正如其他人所建议的,temporary solution 是删除 SSR(服务器端渲染)。这意味着打开 Home/Index.cshtml 文件并更改

<app asp-prerender-module="ClientApp/dist/main-server">Loading...</app>

<app>Loading...</app>

【讨论】:

    【解决方案4】:

    来自mak0t0san 的解决方案为我工作并且 ssr 仍在工作(角度 5.2.0),

    1. 将 ngtoolwebpack 更新到 1.10.2
    2. 打字稿 2.6.2

    并用它更改 webpack.config.js

    const path = require('path');
    const webpack = require('webpack');
    const { DllReferencePlugin, SourceMapDevToolPlugin} = require('webpack');
    const merge = require('webpack-merge');
    const {AngularCompilerPlugin, PLATFORM} = require('@ngtools/webpack');
    const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
    const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
    
    module.exports = (env) => {
        // Configuration in common to both client-side and server-side bundles
        const isDevBuild = !(env && env.prod);
        const sharedConfig = {
            stats: {modules: false},
            context: __dirname,
            resolve: {extensions: ['.js', '.ts']},
            output: {
                filename: '[name].js',
                chunkFilename:'[id].chunk.js',
                publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
            },
            module: {
                rules: [
                    {test: /\.html$/, use: 'html-loader?minimize=false'},
                    {test: /\.css$/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize']},
                    {test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000'},
                    {
                        test: /\.(scss)$/,
                        use: [{
                            loader: 'style-loader', // inject CSS to page
                        }, {
                            loader: 'css-loader', // translates CSS into CommonJS modules
                        }, {
                            loader: 'postcss-loader', // Run post css actions
                            options: {
                                plugins: function () { // post css plugins, can be exported to postcss.config.js
                                    return [
                                        require('precss'),
                                        require('autoprefixer')
                                    ];
                                }
                            }
                        }, {
                            loader: 'sass-loader' // compiles Sass to CSS
                        }]
                    }
                ]
            },
            plugins: [new CheckerPlugin()]
        };
    
        // Configuration for client-side bundle suitable for running in browsers
        const clientBundleOutputDir = './wwwroot/dist';
        const clientBundleConfig = merge(sharedConfig, {
            module:{
                rules:[
                    {
                        test: /\.ts$/,
                        use: ['@ngtools/webpack']
                    },
                ]
            },
            entry: {'main-client': './ClientApp/boot.browser.ts'},
            output: {path: path.join(__dirname, clientBundleOutputDir)},
            plugins: [
                new DllReferencePlugin({
                    context: __dirname,
                    manifest: require('./wwwroot/dist/vendor-manifest.json')
                }),
                new AngularCompilerPlugin({
                    "mainPath": path.join(__dirname, 'ClientApp/boot.browser.ts'),
                    platform: PLATFORM.Browser,
                    tsConfigPath: './tsconfig.json',
                    entryModule: path.join(__dirname, 'ClientApp/app/app.browser.module#AppModule'),
                    sourceMap: true
                })
            ].concat(isDevBuild ? [
                // Plugins that apply in development builds only
                new SourceMapDevToolPlugin({
                    filename: '[file].map', // Remove this line if you prefer inline source maps
                    moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
                })
            ] : [
                // Plugins that apply in production builds only
              new UglifyJsPlugin({
                    sourceMap: true
                })
            ])
        });
    
        // Configuration for server-side (prerendering) bundle suitable for running in Node
        const serverBundleConfig = merge(sharedConfig, {
            module:{
              rules:[
                  { test: /\.ts$/, use: ['awesome-typescript-loader?silent=true', 'angular2-template-loader', 'angular2-router-loader'] },
              ]
            },
            resolve: { mainFields: ['main'] },
            entry: { 'main-server': './ClientApp/boot.server.ts' },
            plugins: [
                new webpack.DllReferencePlugin({
                    context: __dirname,
                    manifest: require('./ClientApp/dist/vendor-manifest.json'),
                    sourceType: 'commonjs2',
                    name: './vendor'
                })
            ],
            output: {
                libraryTarget: 'commonjs',
                path: path.join(__dirname, './ClientApp/dist')
            },
            target: 'node',
            devtool: 'inline-source-map'
        });
    
    
        return [clientBundleConfig, serverBundleConfig];
    };
    

    【讨论】:

      【解决方案5】:

      正如@MMiebach 的link 所写:

      Angular 5 包含重大更改(相对于 Angular 4),这意味着服务器端渲染的代码必须非常不同。

      幸运的是,微软发布了their new SPA project template for Angular 5。可以安装

      dotnet new --install Microsoft.DotNet.Web.Spa.ProjectTemplates::2.0.0
      

      在该命令之后dotnet new angular 将使用第 5 个 Angular 而不是第 4 个。

      默认情况下,服务端渲染是不开启的,但是Docs by MS有说明如何开启。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-08
        • 2019-08-14
        • 2018-05-09
        • 2023-03-16
        • 2020-10-16
        • 1970-01-01
        • 2019-05-30
        相关资源
        最近更新 更多