一旦我构建了 main.js,我就会使用 Angular 6,当我们构建这个应用程序时,我预计它会变得更大,main.js 大约为 8 MB。有没有办法将此文件拆分为多个文件,以便加载速度更快?有没有办法在需要的时候实现延迟加载。
chunk {0} runtime.ec2944dd8b20ec099bf3.js (runtime) 1.44 kB [entry] [rendered]
chunk {1} main.d2ed080a489df2acb65c.js (main) 8.27 MB [initial] [rendered]
chunk {2} polyfills.991eda935898a57f5c1f.js (polyfills) 59.6 kB [initial] [rendered]
chunk {3} styles.5bc2644258354e9b9ba3.css (styles) 680 kB [initial] [rendered]
chunk {scripts} scripts.92795880e21717c67f9d.js (scripts) 40.3 kB [rendered]
角度.json
"configurations": {
"production": {
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
]
},
最佳答案
首先,我强烈建议您更新 Angular 版本。
是的,您可以将 main.js
拆分为几个 block ,但我认为延迟加载是使应用程序更快的方法。
Angular CLI 拆分块步骤
来自 docs :使用Angular CLI
选项,您可以拆分common
和vendor
block 。
您可以将这些设置添加到项目的 angular.json
中或直接使用它:
ng build --commonChunk --vendorChunk
但我认为这些选项在 Angular v6 中可能不可用。
无论如何,您可以使用自定义构建器执行相同的操作(见下文)。
自定义拆分块步骤
更改 angular.json 中的构建器并添加 webpack.config.js 的路径以使用自定义 webpack 配置进行构建和服务:
"build": {
"builder": "@angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {
"path": "./webpack.config.js"
},
...
"serve": {
"builder": "@angular-builders/custom-webpack:dev-server",
在 webpack.config.js
中,你可以做 webpack 能做的一切。以下是共享
block 的示例:
module.exports = function(base) {
return {
...base,
optimization: {
...base.optimization,
splitChunks: {
...base.optimization.splitChunks,
cacheGroups: {
...base.optimization.splitChunks.cacheGroups,
myCustomChunk: {
test: /MyCustomRegexpToGrabFiles/, // search files by pattern
enforce: true, // always split this chunk
name: 'myCustomChunk', // name will be myCustomChunk.js
chunks: 'all' // split it from lazy and common chunks
}
}
}
}
}
}
有关更多示例,请查看 SplitChunksPlugin docs .
延迟加载步骤
使用 webpack 进行延迟加载总是会创建单独的 block 。
基本上你应该遵循这个guide适用于 Angular v6。
关于webpack - 将Angular6中的main.js拆分为多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54062744/