首页 > 解决方案 > 升级到 Angular 8.3.5 后,Angular 应用程序不加载应用程序模块/组件

问题描述

我们有一个Angular 4项目,我最近尝试升级到Angular 8. 我遵循了 Angular 网站上的迁移指南,更改了一些语法,以及阻止项目构建的所有内容。我面临的问题是我的样式在本地没有正确加载,在 Azure 上根本没有。我找到Webpack并尝试配置它,添加了 style-loader、sass-loader 和 css-loader。现在,当我在本地运行时,我可以在浏览器的网络选项卡中看到所有样式都正确加载,但它只加载默认的 index.html 文件,而不是引导应用程序。

当我在 Azure 上部署应用程序时,它会加载其他组件,但没有加载任何样式。我花了 3 周的时间进行迁移,但还没有任何希望。

工具/插件版本:

Angular CLI: 8.3.5
Node: 10.15.1
OS: win32 x64
Angular: 8.2.7
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... platform-server, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.803.5
@angular-devkit/build-angular     0.803.5
@angular-devkit/build-optimizer   0.803.5
@angular-devkit/build-webpack     0.803.5
@angular-devkit/core              8.3.5
@angular-devkit/schematics        8.3.5
@angular/cdk                      8.2.0
@angular/cli                      8.3.5
@angular/http                     5.2.11
@angular/material                 8.2.0
@ngtools/webpack                  8.3.5
@schematics/angular               8.3.5
@schematics/update                0.803.5
rxjs                              6.5.3
typescript                        3.5.3
webpack                           4.40.2

这是我的 Webpack 配置:

const { resolve } = require('path');
const rxPaths = require('rxjs/_esm5/path-mapping');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ProgressPlugin = require('webpack/lib/ProgressPlugin');
const CircularDependencyPlugin = require('circular-dependency-plugin');
const { AngularCompilerPlugin } = require('@ngtools/webpack');
const { IndexHtmlWebpackPlugin } = require('@angular-devkit/build-angular/src/angular-cli-files/plugins/index-html-webpack-plugin');

module.exports = {

  mode: 'development',

  devtool: 'eval',

  entry: {
    main: './src/main.ts',
    polyfills: './src/polyfills.ts',
    styles: './src/styles.scss'
  },

  output: {
    path: resolve('./dist/'),
    filename: '[name].js',
  },

  resolve: {
    extensions: ['.ts', '.js'],
    alias: rxPaths()
  },

  node: false,

  performance: {
    hints: false,
  },

  module: {
    rules: [
      {
        test: /\.ts$/,
        use: '@ngtools/webpack'
      },
      {
        test: /\.js$/,
        exclude: /(ngfactory|ngstyle).js$/,
        enforce: 'pre',
        use: 'source-map-loader'
      },
      {
        test: /\.html$/,
        use: 'raw-loader'
      },
      {
        test: /\.s[ac]ss$/i,
        use: ['sass-loader'],
        // use: ['to-string-loader, css-loader, sass-loader'],
        exclude: [resolve('./src/styles.scss')]
      },
      {
        test: /\.s[ac]ss$/i,
        // use: ['sass-loader'],
        include: [resolve('./src/styles.scss')]
      },
      {
        test: /\.(eot|svg|cur)$/,
        loader: 'file-loader',
        options: {
          name: `[name].[ext]`,
          limit: 10000
        }
      },
      {
        test: /\.(jpg|png|webp|gif|otf|ttf|woff|woff2|ani)$/,
        loader: 'url-loader',
        options: {
          name: `[name].[ext]`,
          limit: 10000
        }
      },

      // This hides some deprecation warnings that Webpack throws

      {
        test: /[\/\\]@angular[\/\\]core[\/\\].+\.js$/,
        parser: { system: true },
      }
    ]
  },

  plugins: [
    new IndexHtmlWebpackPlugin({
      input: 'index.html',
      output: 'index.html',
      inject: 'body',
      entrypoints: [
        'styles',
        'polyfills',
        'main'
      ]
    }),

    new AngularCompilerPlugin({
      mainPath: resolve('./src/main.ts'),
      sourceMap: true,
      nameLazyFiles: true,
      tsConfigPath: resolve('./src/tsconfig.app.json')
      // ,
      // skipCodeGeneration: true
    }),

    new ProgressPlugin(),

    new CircularDependencyPlugin({
      exclude: /[\\\/]node_modules[\\\/]/
    }),

    new CopyWebpackPlugin([
      {
        from: 'src/assets',
        to: 'assets'
      },
      {
        from: 'src/favicon.ico'
      }
    ])
  ]
};

请注意,我在 Webpack 配置中评论 use[] 的原因是它抛出了一些 postcss-loader 异常,并且在 Github 上的一个问题上发现默认 sass-loader 和 Webpack 会发生一些冲突,你应该删除它们。

这是 angular.json 中的构建配置

        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "customWebpackConfig": {
              "path": "./webpack.config.js",
              "replaceDuplicatePlugins": true
            },
            "outputPath": "./dist/",
            "index": "src/index.html",
            "main": "src/main.ts",
            "tsConfig": "src/tsconfig.app.json",
            "polyfills": "src/polyfills.ts",
            "assets": [
              "src/assets",
              "src/config",
              "src/favicon.ico"
            ],
            "styles": [
              "./src/styles.scss"
            ],
            "scripts": [
              "node_modules/jquery/dist/jquery.min.js",
              "node_modules/bootstrap/dist/js/bootstrap.min.js",
              "node_modules/metismenu/dist/metisMenu.js",
              "node_modules/vis/dist/vis.min.js",
              "vendor/js/jvectormap/jquery-jvectormap-2.0.2.min.js",
              "vendor/js/jvectormap/jquery-jvectormap-us-mill.js",
              "vendor/js/iCheck/icheck.js",
              "node_modules/toastr/toastr.js"
            ]
          },
          "configurations": {
            "dev": {
              "optimization": true,
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.dev.ts"
                }
              ]
            },
            "local": {
              "optimization": true,
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            },
            "production": {
              "optimization": true,
              "sourceMap": false,
              "extractCss": false,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "styles": [
                "./src/styles.scss"
              ]
            }
          }
        },

这是 Angular.json 中的服务配置。

"serve": {
          "builder": "@angular-builders/custom-webpack:dev-server",
          "options": {
            "browserTarget": "projectName:build",
            "customWebpackConfig": {
              "path": "./webpack.config.js"
            }
          },
          "configurations": {
            "local":{
              "browserTarget": "projectName:build:local"
            }
            ,
            "dev": {
              "browserTarget": "projectName:build:dev"
            },
            "production": {
              "browserTarget": "projectName:build:production"
            }
          }
        },

我已经使用@import 语句在styles.scss 中导入了所有样式。我不确定的一件事是我正在使用 Highcharts 并在构建过程中收到一些警告。

WARNING in ./node_modules/angular2-highcharts/dist/index.js
Module Warning (from ./node_modules/source-map-loader/index.js):
(Emitted value instead of an instance of Error) Cannot find source file '../src/index.ts': Error: Can't resolve '../src/index.ts'

除此之外,项目中没有编译/运行时错误。

感谢您花时间阅读我的问题。我感谢任何提示/提示。

更新: 这是项目结构的样子:

|   .editorconfig
|   .gitignore
|   angular.json
|   browserslist
|   karma.conf.js
|   package-lock.json
|   package.json
|   protractor.conf.js
|   README.md
|   tsconfig.json
|   tslint.json
|   webpack.config.js
|          
+---src
|   |   favicon.ico
|   |   index.html
|   |   index.js
|   |   main.ts
|   |   polyfills.ts
|   |   styles.scss
|   |   test.ts
|   |   tsconfig.app.json
|   |   tsconfig.spec.json
|   |   typings.d.ts
|   |   webpack.config.common.js
|   |   
|   +---app       
|   +---assets
|   |   |
|   |   +---images
|   |   \---styles
|   |       |   style.scss
|   |       |   
|   |               
|   +---config
|   |       dev-config.js
|   |       local-config.js
|   |       prod-config.js
|   |       qa-config.js
|   |       
|   +---environments
|   |       environment.dev.ts
|   |       environment.prod.ts
|   |       environment.qa.ts
|   |       environment.ts
 

标签: angularwebpackangular8webpack-style-loaderangular-upgrade

解决方案


如果我理解正确,主要问题是没有应用样式。

您正在根据 config: 的这一行使用 Bootstrap 文件"node_modules/bootstrap/dist/js/bootstrap.min.js",但是您尚未将此样式导入最终捆绑包。所以尝试将其写入angular.json文件:

"styles": [
          "node_modules/bootstrap/dist/css/bootstrap.min.css",
          "src/styles.scss"
],

此外,您需要导入 bootstrap样式以在应用程序中使用它们到style.scss文件中:

/* You can add global styles to this file, and also import other style files */
@import "~bootstrap/dist/css/bootstrap.css";

<!-- 
     h1, h2, h3 {
         margin-bottom: 1.5rem;
     } 
-->

更新:

  1. 通过 Angular CLI 创建后,我们app.module.ts应该如下所示:

    @NgModule({
        declarations: [
        AppComponent
        ],
        imports: [
            BrowserModule,
            AppRoutingModule
        ],
        providers: [],
        bootstrap: [AppComponent]
    })
    export class AppModule { }
    

每个应用程序都应该有一个起点。在 Angular 中,我们有一个约定,我们的应用程序应该从AppModule. AppModule是我们的路由模块。所以我们告诉 Angular,当它AppModule在开始时创建我们的根模块()时,我们希望将其设置为DOMAppComponent的起点( )。bootstrap

将引导您的应用程序的代码放入main.ts文件中:

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.error(err));

上面的代码使用 Just in Time 编译。

让我展示一下index.html外观:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Frontend</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>

<app-root></app-root>的选择器在哪里app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'Frontend';
  test = {};
}

您可以通过替换为index.html.

仔细检查您的选择器 app.component.htmlindex.html.

  1. 尝试在文件serve部分将 projectName 设置为您的项目名称angular.json。例如,如果你的项目被命名为superappl,那么你应该这样写:

    serve": {
      "builder": "@angular-builders/custom-webpack:dev-server",
      "options": {
        "browserTarget": "superappl:build",
        "customWebpackConfig": {
          "path": "./webpack.config.js"
        }
      },
      "configurations": {
        "local":{
          "browserTarget": "superappl:build:local"
        }
        ,
        "dev": {
          "browserTarget": "superappl:build:dev"
        },
        "production": {
          "browserTarget": "superappl:build:production"
        }
      }
    },
    
  2. 如果上述操作不会运行您的应用程序。Angular CLI然后我建议您使用并比较您的index.html文件和文件来创建新的品牌应用程序app.module.ts。创建新品牌应用程序以比较现有应用程序(尤其是package.json文件angular.json)的命令:

    npm install -g @angular/cli
    ng new angular-newapp --skip-install
    npm install @angular/core@latest
    npm install @angular/http@latest
    npm install
    ng serve
    

一些问题:

  1. 你是手动创建的Webpack.config吗?使用它的理由是什么?Webpack config如果它适用于您,您可以避免使用和调整。因为默认情况下 Angular CLI 不会创建这个文件。您应该手动编写ng-eject命令来获取 webpack 文件。

  2. 你可以发布你的index.htmlandapp.module.ts吗?

  3. 当您在本地运行应用程序时,您的应用程序是否正常工作?我的意思是当你运行命令时ng serve

推荐阅读