Angular13 What should I do if the development mode is too slow? The following article will introduce to you the reasons why Angular 13 development mode is too slow and how to optimize build performance. I hope it will be helpful to you!
Recently worked on a high-frequency Angular project for seven years After upgrading to Angular 13, its development mode has slow construction speed, high resource usage, and poor development experience. When launching a build on a Macbook air
that I only use occasionally for meetings (and has recently become my primary productivity tool during the work-from-home period), its fans whir, the CPU is maxed out, and After the build is completed, a hot update takes more than one minute. [Related tutorial recommendations: "angular Tutorial"]
After analyzing and troubleshooting various reasons, we finally found the schema(. /node_modules/@angular/cli/lib/config/schema.json
), and combined with Angular 12 release document
, the specific cause was located: A major change in Angular 12 is to aot, buildOptimizer
, optimization
and other parameters have been changed from the default value false
to true
.
You can see that the default production mode after Angular 12 is quite tricky for cross-version upgrades. We can learn the details of the changes from this submission:656f8d71.1 Solve the problem of slow development mode of Angular 12
Disable configuration items related to production mode in the configuration. Example: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">{
"$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"
}</pre><div class="contentsignin">Copy after login</div></div>
Note
When it is turned on and off, there may be some differences in the performance of the build results, which need to be analyzed based on the specific problem.
pug
compiles and reports an error
is used in this project Develop html content. The build is normal when aot
is turned off, but an error will be reported when turned on. Perform debugger debugging based on the error content and location. You can see that the compilation result is an esModule object. This is due to the use of
, whose compilation result defaults to esModule
mode, just disable the esModule
configuration item. Example (for custom webpack configuration, please refer to the dll configuration related examples below): <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">{
test: /\.pug$/,
use: [
{
loader: &#39;raw-loader&#39;,
options: {
esModule: false,
},
},
{
loader: &#39;pug-html-loader&#39;,
options: {
doctype: &#39;html&#39;,
},
},
],
},</pre><div class="contentsignin">Copy after login</div></div>
configuration, which is implemented using the @angular-builders/custom-webpack
library, but no dll is configured.
provides the vendorChunk
parameter. Turning it on will extract public resources such as dependencies in package.json
into independent chunks. It can well solve the problem of hot update bundles being too large, causing hot update to be too slow, etc., but there is still a high memory usage, and in the actual comparison test, in the presence of webpack5 cache, it is better than the dll mode build The compilation speed and hot update speed are slightly slower. Therefore, when the performance of the development machine is average, configuring the dll in the development mode will bring certain benefits.
npm i -D @angular-builders/custom-webpack
Modify
angluar.json configuration. Content format reference: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">{
"$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
}
}
}</pre><div class="contentsignin">Copy after login</div></div>
This example involves many custom configuration contents. You should mainly pay attention to the webpack-related parts. Other contents can be compared and referenced based on the specific situation of your own project. For some details, you can also refer to the practical introduction in this previous article:
file. Content reference: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">const { existsSync } = require(&#39;node:fs&#39;);
const { resolve } = require(&#39;node:path&#39;);
const webpack = require(&#39;webpack&#39;);
// require(&#39;events&#39;).EventEmitter.defaultMaxListeners = 0;
/**
* @param {import(&#39;webpack&#39;).Configuration} config
* @param {import(&#39;@angular-builders/custom-webpack&#39;).CustomWebpackBrowserSchema} options
* @param {import(&#39;@angular-builders/custom-webpack&#39;).TargetOptions} targetOptions
*/
module.exports = (config, options, targetOptions) => {
if (!config.devServer) config.devServer = {};
config.plugins.push(
new webpack.DefinePlugin({ LZWME_DEV: config.mode === &#39;development&#39; }),
);
const dllDir = resolve(__dirname, &#39;./dist/dll&#39;);
if (
existsSync(dllDir) &&
config.mode === &#39;development&#39; &&
options.scripts?.some((d) => d.bundleName === &#39;dll_library&#39;)
) {
console.log(&#39;use dll:&#39;, dllDir);
config.plugins.unshift(
new webpack.DllReferencePlugin({
manifest: require(resolve(dllDir, &#39;dll-manifest.json&#39;)),
context: __dirname,
})
);
}
config.module.rules = config.module.rules.filter((d) => {
if (d.test instanceof RegExp) {
// 使用 less,移除 sass/stylus loader
return !(d.test.test(&#39;x.sass&#39;) || d.test.test(&#39;x.scss&#39;) || d.test.test(&#39;x.styl&#39;));
}
return true;
});
config.module.rules.unshift(
{
test: /\.pug$/,
use: [
{
loader: &#39;raw-loader&#39;,
options: {
esModule: false,
},
},
{
loader: &#39;pug-html-loader&#39;,
options: {
doctype: &#39;html&#39;,
},
},
],
},
{
test: /\.html$/,
loader: &#39;raw-loader&#39;,
exclude: [helpers.root(&#39;src/index.html&#39;)],
},
{
test: /\.svg$/,
loader: &#39;raw-loader&#39;,
},
{
test: /\.(t|les)s/,
loader: require.resolve(&#39;@lzwme/strip-loader&#39;),
exclude: /node_modules/,
options: {
disabled: config.mode !== &#39;production&#39;,
},
}
);
// AngularWebpackPlugin,用于自定义 index.html 处理插件
const awPlugin = config.plugins.find((p) => p.options?.hasOwnProperty(&#39;directTemplateLoading&#39;));
if (awPlugin) awPlugin.pluginOptions.directTemplateLoading = false;
// 兼容上古遗传逻辑,禁用部分插件
config.plugins = config.plugins.filter((plugin) => {
const pluginName = plugin.constructor.name;
if (/CircularDependency|CommonJsUsageWarnPlugin/.test(pluginName)) {
console.log(&#39;[webpack][plugin] disabled: &#39;, pluginName);
return false;
}
return true;
});
// console.log(&#39;[webpack][config]&#39;, config.mode, config, options, targetOptions);
return config;
};</pre><div class="contentsignin">Copy after login</div></div>
Create a new
file for dll building. Content example: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">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`);
});</pre><div class="contentsignin">Copy after login</div></div><p>在 <code>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
测试效果是否符合预期。
angular-cli
在升级至 webpack 5 以后,基于 webpack 5 的缓存能力做了许多编译优化,一般情况下开发模式二次构建速度相比之前会有大幅的提升。但是相比 snowpack
和 vite
一类的 esm no bundles 方案仍有较大的差距。其从 Angular 13
开始已经在尝试引入 esbuild
,但由于其高度定制化的构建逻辑适配等问题,对一些配置参数的兼容支持相对较为复杂。在 Angular 15
中已经可以进行生产级配置尝试了,有兴趣也可作升级配置与尝试。
更多编程相关知识,请访问:编程教学!!
The above is the detailed content of What should I do if Angular13+ development mode is too slow? Causes and solutions. For more information, please follow other related articles on the PHP Chinese website!