Angular13+ 개발 모드가 너무 느리면 어떻게 해야 합니까? 원인과 해결책

青灯夜游
풀어 주다: 2023-01-13 20:23:49
앞으로
2507명이 탐색했습니다.

Angular13+ 개발 모드가 너무 느리면 어떻게 해야 하나요? 다음 글에서는 Angular 13+ 개발 모드가 너무 느린 이유와 빌드 성능을 최적화하는 방법을 소개하겠습니다. 도움이 되길 바랍니다.

Angular13+ 개발 모드가 너무 느리면 어떻게 해야 합니까? 원인과 해결책

1 Angular 13+의 느린 개발 모드에 대한 이유와 해결책

최근 7년 동안 높은 빈도로 반복되는 Angular 프로젝트가 Angular 13으로 업그레이드된 후 개발 모드가 빌드되고 점유되는 속도가 느려졌습니다. 자원이 많고 개발 경험이 매우 열악합니다. 가끔 회의용으로만 사용하는(최근에는 재택근무 기간 동안 주요 생산성 도구로 사용) Macbook air에서 빌드를 시작할 때 팬이 윙윙거리고 CPU가 최대치로 사용됩니다. . 빌드가 완료된 후 핫 업데이트는 1분 이상 소요됩니다. [관련 튜토리얼 추천 : "Angular 튜토리얼"]Macbook air(近期居家办公期间转换为了主要生产力工具) 中启动构建时,它的风扇会呼呼作响,CPU 负荷被打满,而在构建完成后,热更新一次的时间在一分钟以上。【相关教程推荐:《angular教程》】

在经过各种原因分析与排查后,最终在 angular.json 的 schema(./node_modules/@angular/cli/lib/config/schema.json) 中发现了问题,再结合 Angular 12 release 文档定位到了具体原因: Angular 12 一个主要的改动是将 aotbuildOptimizeroptimization 等参数由默认值 false 改为了 true

A number of browser and server builder options have had their default values changed. The aim of these changes is to reduce the configuration complexity and support the new "production builds by default" initiative.

可以看到 Angular 12 后的默认生产模式,对于跨版本升级来说是比较坑爹的。我们可以从这个提交中了解变动细节:656f8d7

1.1 解决 Angular 12+ 开发模式慢的问题

解决办法则是在 development 配置中禁用生产模式相关的配置项。示例:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "projects": {
    "front": {
      "architect": {
        "build": {
          "configurations": {
            "development": {
              "tsConfig": "./tsconfig.dev.json",
              "aot": false,
              "buildOptimizer": false,
              "optimization": false,
              "extractLicenses": false,
              "sourceMap": true,
              "vendorChunk": true,
              "namedChunks": true
            }
          }
        },
    }
  },
  "defaultProject": "front"
}
로그인 후 복사

需注意 aot 开启与关闭时,在构建结果表现上可能会有一些差异,需视具体问题而分析。

1.2 问题:开启 aotpug 编译报错

该项目中使用 pug 开发 html 内容。关闭 aot 时构建正常,开启后则会报错。

根据报错内容及位置进行 debugger 调试,可以看到其编译结果为一个 esModule 的对象。这是由于使用了 raw-loader,其编译结果默认为 esModule 模式,禁用 esModule 配置项即可。示例(自定义 webpack 配置可参考下文的 dll 配置相关示例):

{
  test: /\.pug$/,
  use: [
    {
      loader: 'raw-loader',
      options: {
        esModule: false,
      },
    },
    {
      loader: 'pug-html-loader',
      options: {
        doctype: 'html',
      },
    },
  ],
},
로그인 후 복사

2 进一步优化:Angular 自定义 webpack 配置 dll 支持

该项目项目构建上有自定义 webpack 配置的需求,使用了 @angular-builders/custom-webpack 库实现,但是没有配置 dll。

Angular 提供了 vendorChunk 参数,开启它会提取在 package.json 中的依赖等公共资源至独立 chunk 中,其可以很好的解决热更新 bundles 过大导致热更新太慢等的问题,但仍然存在较高的内存占用,而且实际的对比测试中,在存在 webpack5 缓存的情况下,其相比 dll 模式的构建编译速度以及热更新速度都稍微慢一些。故对于开发机器性能一般的情况下,给开发模式配置 dll 是会带来一定的收益的。

2.1 Angular 支持自定义 webpack 配置

首先需要配置自定义 webpack 配置的构建支持。执行如下命令添加依赖:

npm i -D @angular-builders/custom-webpack
로그인 후 복사

修改 angluar.json 配置。内容格式参考:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "cli": {
    "analytics": false,
    "cache": {
      "path": "node_modules/.cache/ng"
    }
  },
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "front": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {
        "@schematics/angular:component": {
          "style": "less"
        }
      },
      "architect": {
        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "customWebpackConfig": {
              "path": "./webpack.config.js"
            },
            "indexTransform": "scripts/index-html-transform.js",
            "outputHashing": "media",
            "deleteOutputPath": true,
            "watch": true,
            "sourceMap": false,
            "outputPath": "dist/dev",
            "index": "src/index.html",
            "main": "src/app-main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "./tsconfig.app.json",
            "baseHref": "./",
            "assets": [
              "src/assets/",
              {
                "glob": "**/*",
                "input": "./node_modules/@ant-design/icons-angular/src/inline-svg/",
                "output": "/assets/"
              }
            ],
            "styles": [
              "node_modules/angular-tree-component/dist/angular-tree-component.css",
              "src/css/index.less"
            ],
            "scripts": []
          },
          "configurations": {
            "development": {
              "tsConfig": "./tsconfig.dev.json",
              "buildOptimizer": false,
              "optimization": false,
              "aot": false,
              "extractLicenses": false,
              "sourceMap": true,
              "vendorChunk": true,
              "namedChunks": true,
              "scripts": [
                {
                  "inject": true,
                  "input": "./dist/dll/dll.js",
                  "bundleName": "dll_library"
                }
              ]
            },
            "production": {
              "outputPath": "dist/prod",
              "baseHref": "./",
              "watch": false,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": {
                "scripts": true,
                "styles": {
                  "minify": true,
                  "inlineCritical": false
                },
                "fonts": true
              },
              "outputHashing": "all",
              "sourceMap": false,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": false,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          },
          "defaultConfiguration": "production"
        },
        "serve": {
          "builder": "@angular-builders/custom-webpack:dev-server",
          "options": {
            "browserTarget": "front:build",
            "liveReload": false,
            "open": false,
            "host": "0.0.0.0",
            "port": 3002,
            "servePath": "/",
            "publicHost": "localhost.gf.com.cn",
            "proxyConfig": "config/ngcli-proxy-config.js",
            "disableHostCheck": true
          },
          "configurations": {
            "production": {
              "browserTarget": "front:build:production"
            },
            "development": {
              "browserTarget": "front:build:development"
            }
          },
          "defaultConfiguration": "development"
        },
        "test": {
          "builder": "@angular-builders/custom-webpack:karma",
          "options": {
            "customWebpackConfig": {
              "path": "./webpack.test.config.js"
            },
            "indexTransform": "scripts/index-html-transform.js",
            "main": "src/ngtest.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "./tsconfig.spec.json",
            "karmaConfig": "./karma.conf.js",
            "assets": [
              "src/assets/",
              {
                "glob": "**/*",
                "input": "./node_modules/@ant-design/icons-angular/src/inline-svg/",
                "output": "/assets/"
              }
            ],
            "styles": [
              "node_modules/angular-tree-component/dist/angular-tree-component.css",
              "src/css/index.less"
            ],
            "scripts": []
          }
        }
      }
    }
  },
  "defaultProject": "front",
  "schematics": {
    "@schematics/angular:module": {
      "routing": true,
      "spec": false
    },
    "@schematics/angular:component": {
      "flat": false,
      "inlineStyle": true,
      "inlineTemplate": false
    }
  }
}
로그인 후 복사

该示例中涉及多处自定义配置内容,主要需注意 webpack 相关的部分, 其他内容可视自身项目具体情况对比参考。一些细节也可参考以前的这篇文章中的实践介绍:lzw.me/a/update-to…

2.2 为 Angular 配置 webpack dll 支持

新建 webpack.config.js 文件。内容参考:

const { existsSync } = require('node:fs');
const { resolve } = require('node:path');
const webpack = require('webpack');

// require('events').EventEmitter.defaultMaxListeners = 0;

/**
 * @param {import('webpack').Configuration} config
 * @param {import('@angular-builders/custom-webpack').CustomWebpackBrowserSchema} options
 * @param {import('@angular-builders/custom-webpack').TargetOptions} targetOptions
 */
module.exports = (config, options, targetOptions) => {
  if (!config.devServer) config.devServer = {};

  config.plugins.push(
    new webpack.DefinePlugin({ LZWME_DEV: config.mode === 'development' }),
  );

  const dllDir = resolve(__dirname, './dist/dll');
  if (
    existsSync(dllDir) &&
    config.mode === 'development' &&
    options.scripts?.some((d) => d.bundleName === 'dll_library')
  ) {
    console.log('use dll:', dllDir);
    config.plugins.unshift(
      new webpack.DllReferencePlugin({
        manifest: require(resolve(dllDir, 'dll-manifest.json')),
        context: __dirname,
      })
    );
  }

  config.module.rules = config.module.rules.filter((d) => {
    if (d.test instanceof RegExp) {
      // 使用 less,移除 sass/stylus loader
      return !(d.test.test('x.sass') || d.test.test('x.scss') || d.test.test('x.styl'));
    }
    return true;
  });

  config.module.rules.unshift(
    {
      test: /\.pug$/,
      use: [
        {
          loader: 'raw-loader',
          options: {
            esModule: false,
          },
        },
        {
          loader: 'pug-html-loader',
          options: {
            doctype: 'html',
          },
        },
      ],
    },
    {
      test: /\.html$/,
      loader: 'raw-loader',
      exclude: [helpers.root('src/index.html')],
    },
    {
      test: /\.svg$/,
      loader: 'raw-loader',
    },
    {
      test: /\.(t|les)s/,
      loader: require.resolve('@lzwme/strip-loader'),
      exclude: /node_modules/,
      options: {
        disabled: config.mode !== 'production',
      },
    }
  );

  // AngularWebpackPlugin,用于自定义 index.html 处理插件
  const awPlugin = config.plugins.find((p) => p.options?.hasOwnProperty('directTemplateLoading'));
  if (awPlugin) awPlugin.pluginOptions.directTemplateLoading = false;

  // 兼容上古遗传逻辑,禁用部分插件
  config.plugins = config.plugins.filter((plugin) => {
    const pluginName = plugin.constructor.name;
    if (/CircularDependency|CommonJsUsageWarnPlugin/.test(pluginName)) {
      console.log('[webpack][plugin] disabled: ', pluginName);
      return false;
    }

    return true;
  });
  // console.log('[webpack][config]', config.mode, config, options, targetOptions);
  return config;
};
로그인 후 복사

新建 webpack.dll.mjs

다양한 이유 분석 후 문제를 해결해 보니 마침내 angular.json의 스키마(./node_modules/@angular/cli/lib/config/schema.json)에서 문제가 발견되었고, Angular 12 릴리스 문서에서는 구체적인 이유를 찾습니다. Angular 12의 주요 변경 사항은 aot를 대체하는 것입니다. buildOptimizer< /code>, <code>optimization 및 기타 매개변수가 기본값 false에서 true로 변경되었습니다. 🎜
🎜다양한 브라우저 및 서버 빌더 옵션의 기본값이 변경되었습니다. 이러한 변경의 목적은 구성 복잡성을 줄이고 새로운 "기본적으로 프로덕션 빌드" 이니셔티브를 지원하는 것입니다.🎜
🎜예, Angular 12 이후의 기본 프로덕션 모드는 버전 간 업그레이드가 상당히 까다롭다는 것을 알 수 있습니다. 이 커밋에서 변경 세부 사항을 알아볼 수 있습니다: 656f8d7🎜

🎜1.1 느린 Angular 12+ 개발 모드 문제 해결 🎜

🎜해결책은 개발 구성에서 프로덕션 모드 관련 구성 항목을 비활성화하는 것입니다. 예: 🎜
import { join } from &#39;node:path&#39;;
import webpack from &#39;webpack&#39;;

const rootDir = process.cwd();
const isDev = process.argv.slice(2).includes(&#39;--dev&#39;) || process.env.NODE_ENV === &#39;development&#39;;

/** @type {import(&#39;webpack&#39;).Configuration} */
const config = {
  context: rootDir,
  mode: isDev ? &#39;development&#39; : &#39;production&#39;,
  entry: {
    dll: [
      &#39;@angular/common&#39;,
      &#39;@angular/core&#39;,
      &#39;@angular/forms&#39;,
      &#39;@angular/platform-browser&#39;,
      &#39;@angular/platform-browser-dynamic&#39;,
      &#39;@angular/router&#39;,
      &#39;@lzwme/asmd-calc&#39;,
      // more...
    ],
  },
  output: {
    path: join(rootDir, &#39;dist/dll&#39;),
    filename: &#39;dll.js&#39;,
    library: &#39;[name]_library&#39;,
  },
  plugins: [
    new webpack.DllPlugin({
      path: join(rootDir, &#39;dist/dll/[name]-manifest.json&#39;),
      name: &#39;[name]_library&#39;,
    }),
    new webpack.IgnorePlugin({
      resourceRegExp: /^\.\/locale$/,
      contextRegExp: /moment$/,
    }),
  ],
  cache: { type: &#39;filesystem&#39; },
};

webpack(config).run((err, result) => {
  console.log(err ? `Failed!` : `Success!`, err || `${result.endTime - result.startTime}ms`);
});
로그인 후 복사
로그인 후 복사
🎜 aot를 켜고 끌 때 빌드 결과의 성능에 약간의 차이가 있을 수 있으므로 특정 문제에 따라 분석해야 합니다. 🎜

🎜1.2 문제: aot를 켠 후 pug가 컴파일하고 오류🎜

🎜는 이 프로젝트에서 사용됩니다. pug는 HTML 콘텐츠를 개발합니다. aot가 꺼지면 빌드가 정상이지만, 켜진 후에는 오류가 보고됩니다. 🎜🎜 오류 내용과 위치를 기반으로 디버거 디버깅을 수행하면 컴파일 결과가 esModule 객체인 것을 확인할 수 있습니다. 이는 컴파일 결과가 기본적으로 esModule 모드로 설정되는 raw-loader를 사용하기 때문입니다. esModule 구성 항목을 비활성화하면 됩니다. 예(사용자 정의 웹팩 구성은 아래의 dll 구성 관련 예를 참조할 수 있습니다): 🎜
{
    "scripts": {
        "ng:serve": "node --max_old_space_size=8192 node_modules/@angular/cli/bin/ng serve",
        "dll": "node config/webpack.dll.mjs",
        "dev": "npm run dll -- --dev && npm run ng:serve -- -c development",
    }
}
로그인 후 복사
로그인 후 복사

🎜2 추가 최적화: Angular 사용자 정의 웹팩 구성 dll 지원 🎜🎜🎜이 프로젝트는 거기에 구축되어 있습니다. @angular-builders/custom-webpack 라이브러리를 사용하여 구현되는 webpack 구성을 사용자 정의해야 하지만 dll이 구성되어 있지 않습니다. 🎜🎜AngularvendorChunk 매개변수를 제공합니다. 이 매개변수를 켜면 package.json의 종속성과 같은 공개 리소스를 독립적인 청크로 추출할 수 있습니다. 핫 업데이트 번들이 너무 커서 핫 업데이트가 너무 느려지는 등의 문제에 대한 좋은 솔루션이지만 여전히 메모리 사용량이 높으며 실제 비교 테스트에서는 webpack5 캐시가 있는 경우 dll 모드 빌드 및 컴파일보다 낫습니다. 속도와 핫 업데이트 속도가 약간 느립니다. 따라서 개발 시스템의 성능이 평균일 때 개발 모드에서 dll을 구성하면 특정 이점을 얻을 수 있습니다. 🎜

🎜2.1 Angular는 사용자 정의 웹팩 구성을 지원합니다🎜

🎜먼저 사용자 정의 웹팩 구성을 위한 빌드 지원을 구성해야 합니다. 다음 명령을 실행하여 종속성을 추가합니다. 🎜rrreee🎜 angluar.json 구성을 수정합니다. 콘텐츠 형식 참조: 🎜rrreee🎜이 예제에는 사용자 정의 구성 콘텐츠가 많이 포함되어 있으며 주로 webpack 관련 부분에 주의해야 합니다. 다른 콘텐츠는 자신의 프로젝트의 특정 상황에 따라 비교 및 ​​참조될 수 있습니다. 자세한 내용은 이전 기사의 실제 소개를 참조하세요. lzw.me/a/update-to…🎜

🎜2.2 Angular🎜

에 대한 webpack dll 지원 구성🎜새 webpack.config.js 파일을 생성합니다. 콘텐츠 참조: 🎜rrreee🎜dll 빌드를 위한 새 webpack.dll.mjs 파일을 만듭니다. 콘텐츠 예: 🎜
import { join } from &#39;node:path&#39;;
import webpack from &#39;webpack&#39;;

const rootDir = process.cwd();
const isDev = process.argv.slice(2).includes(&#39;--dev&#39;) || process.env.NODE_ENV === &#39;development&#39;;

/** @type {import(&#39;webpack&#39;).Configuration} */
const config = {
  context: rootDir,
  mode: isDev ? &#39;development&#39; : &#39;production&#39;,
  entry: {
    dll: [
      &#39;@angular/common&#39;,
      &#39;@angular/core&#39;,
      &#39;@angular/forms&#39;,
      &#39;@angular/platform-browser&#39;,
      &#39;@angular/platform-browser-dynamic&#39;,
      &#39;@angular/router&#39;,
      &#39;@lzwme/asmd-calc&#39;,
      // more...
    ],
  },
  output: {
    path: join(rootDir, &#39;dist/dll&#39;),
    filename: &#39;dll.js&#39;,
    library: &#39;[name]_library&#39;,
  },
  plugins: [
    new webpack.DllPlugin({
      path: join(rootDir, &#39;dist/dll/[name]-manifest.json&#39;),
      name: &#39;[name]_library&#39;,
    }),
    new webpack.IgnorePlugin({
      resourceRegExp: /^\.\/locale$/,
      contextRegExp: /moment$/,
    }),
  ],
  cache: { type: &#39;filesystem&#39; },
};

webpack(config).run((err, result) => {
  console.log(err ? `Failed!` : `Success!`, err || `${result.endTime - result.startTime}ms`);
});
로그인 후 복사
로그인 후 복사

angular.json 中添加 dll.js 文件的注入配置,可参考前文示例中 development.scripts 中的配置内容格式。

package.json 中增加启动脚本配置。示例:

{
    "scripts": {
        "ng:serve": "node --max_old_space_size=8192 node_modules/@angular/cli/bin/ng serve",
        "dll": "node config/webpack.dll.mjs",
        "dev": "npm run dll -- --dev && npm run ng:serve -- -c development",
    }
}
로그인 후 복사
로그인 후 복사

最后,可执行 npm run dev 测试效果是否符合预期。

3 小结

angular-cli 在升级至 webpack 5 以后,基于 webpack 5 的缓存能力做了许多编译优化,一般情况下开发模式二次构建速度相比之前会有大幅的提升。但是相比 snowpackvite 一类的 esm no bundles 方案仍有较大的差距。其从 Angular 13 开始已经在尝试引入 esbuild,但由于其高度定制化的构建逻辑适配等问题,对一些配置参数的兼容支持相对较为复杂。在 Angular 15 中已经可以进行生产级配置尝试了,有兴趣也可作升级配置与尝试。

更多编程相关知识,请访问:编程教学!!

위 내용은 Angular13+ 개발 모드가 너무 느리면 어떻게 해야 합니까? 원인과 해결책의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:juejin.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!