使用angular cli 7在生产包中添加延迟/异步操作

时间:2019-02-20 12:39:49

标签: angular webpack

在新网站上,我在使用移动浏览器专用的angular cli 7生产时遇到了一些性能问题,经检查后,我发现性能不佳的主要原因是在我为角度cli生成的JavaScript包中缺少pre / async 。

我想知道是否有其他方法可以使用angular cli 7来在最终捆绑包中添加defer / async,我尝试进行搜索,但发现旧的cli cli版本的许多替代方法都包含一个功能建议,但没有对于新版本,因为自从有角度的版本6起,就不可能弹出webpack配置并自定义,添加插件等。

1 个答案:

答案 0 :(得分:0)

角度cli部分没有神奇的解决方案,但是我发现了对我来说很好的自定义构建器。

https://www.npmjs.com/package/@angular-builders/custom-webpack#custom-webpack-config-object

angular-cli.json

  "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "outputPath": "dist/browser",
            "index": "src/index.html",
            "main": "src/main.ts",
            "tsConfig": "src/tsconfig.app.json",
            "polyfills": "src/polyfills.ts",
            "assets": [
              "src/assets",
              "src/favicon.ico"              
            ],
            "styles": [
              "node_modules/bootstrap/dist/css/bootstrap.min.css",
              "node_modules/photoswipe/dist/photoswipe.css",
              "node_modules/photoswipe/dist/default-skin/default-skin.css",
              "src/styles.scss"
            ],
            "scripts": [],
            "customWebpackConfig": {
              "path": "./webpack-extra.config.js",
              "mergeStrategies": {"plugins": "replace"}             
            }
          },

webpack-extra.config

const HtmlWebpackPlugin = require('html-webpack-plugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');

module.exports = {
    plugins: [
        new HtmlWebpackPlugin({
                 "template": "./src\\index.html",
                 "filename": "./index.html",
                 "hash": false,
                 "inject": true,
                 "compile": true,
                 "favicon": false,
                 "minify": {
                   "caseSensitive": true,
                   "collapseWhitespace": true,
                   "keepClosingSlash": true,
                   "removeComments": true,
                   "removeRedundantAttributes": true
                 },
                 "cache": true,
                 "showErrors": true,
                 "chunks": "all",
                 "excludeChunks": [],
                 "title": "Webpack App",
                 "xhtml": true,
                 "chunksSortMode": "none"
               }),
        new ScriptExtHtmlWebpackPlugin({
            defaultAttribute: 'defer'
          }),
        new CompressionPlugin({
          test: /\.js(\?.*)?$/i          
        })
    ]
};