【问题标题】:Angular Application Doesn't load up App Module/Components after Upgrade to Angular 8.3.5升级到 Angular 8.3.5 后,Angular 应用程序不加载应用程序模块/组件
【发布时间】:2020-01-27 09:03:05
【问题描述】:

我们有一个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
 

【问题讨论】:

  • 几天前我也遇到了同样的问题。我还在寻找它。
  • 请发布您的项目结构。
  • 期待看到解决方案
  • @MustafaMohammadi 你不认为你在这里错过了什么“改变了一些语法”吗?
  • 我之前解决了这种问题(将角度4升级到角度7)

标签: angular webpack angular8 webpack-style-loader angular-upgrade


【解决方案1】:

项目中缺少文件 index.ts,似乎文件 index.js 扩展名已从 ts 更改为 js,它正在寻找它作为 ts。

尝试使用 src 文件夹中的 index.ts 更改 index.js 扩展名。

【讨论】:

  • @MustafaMohammadi 为什么使用index.js 文件?是为了什么? index.html 用于作为应用程序的占位符,但是,不需要代码。你能显示index.js文件的内容吗?
【解决方案2】:

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

您正在根据配置的这一行使用引导文件:"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. 我们的app.module.ts 在通过 Angular CLI 创建后应该如下所示:

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

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

将引导您的应用程序的代码放入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));

以上代码使用即时编译。

让我来看看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>

其中&lt;app-root&gt;&lt;/app-root&gt;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.html 的选择器和index.html 中使用的选择器。

  1. 尝试在angular.json 文件的serve 部分中将 projectName 设置为您的项目名称。例如,如果你的项目被命名为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.jsonangular.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.htmlapp.module.ts 吗?

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

【讨论】:

  • 样式现在可以正确加载,(正如我在网络选项卡中看到的那样)。当前的问题是,当我运行应用程序时,它只加载默认的 index.html 文件。不启动 AppModule。具体来说,它应该重定向到登录页面或仪表板,但事实并非如此。当我在浏览器中输入 localhost/login 时,文档会在网络选项卡中加载,但组件不会加载。只是停留在默认 index.html
  • 在 Azure 上,确实没有加载样式。关于引导程序,我已按照 Angular 文档的建议导入到 styles.scss 文件中。
  • 非常感谢您花时间回答问题。我一定会尝试所有这些。但他们中的大多数已经被检查过。我这周很忙,会尽快发布更新。
  • @MustafaMohammadi 欢迎您!相信会对你有所帮助! :)
【解决方案3】:

我以前这样解决过这种问题:

第 1 步:删除 node_modules

第 2 步:npm i

第 3 步(如果不起作用):npm rebuild node-sass

就我而言,它运行良好。

希望对你有所帮助。

【讨论】:

  • 不幸的是没有运气
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-26
  • 2018-03-01
  • 2021-08-18
  • 2019-12-27
  • 2017-12-08
  • 2018-01-23
相关资源
最近更新 更多