Inconsistent bundle output between ng build and ng build --watch

Viewed 996

How come that angular produces different bundles when running a regular ng build vs ng build --watch?

I have verified this by running ng build & ng build --watch on an app created with ng new.

I need to know what the bundle names is beforehand because they will be served with ASP.NET's BundleConfig, which is why I would like the build output to be consistent between a regular build and a build with the watch flag.

I am using Angular 8.

As you can see below the ng build --watch produces build output which doesn't have es5/es2015 appended to the bundle names, except for polyfills.

$ ng build

Date: 2019-06-05T06:48:01.672Z
Hash: 36c34ee221d2ae159bb9
Time: 6625ms
chunk {main} main-es5.js, main-es5.js.map (main) 10.4 kB [initial] [rendered]
chunk {polyfills} polyfills-es5.js, polyfills-es5.js.map (polyfills) 546 kB [initial] [rendered]
chunk {runtime} runtime-es5.js, runtime-es5.js.map (runtime) 6.08 kB [entry] [rendered]
chunk {styles} styles-es5.js, styles-es5.js.map (styles) 16.7 kB [initial] [rendered]
chunk {vendor} vendor-es5.js, vendor-es5.js.map (vendor) 3.7 MB [initial] [rendered]

Date: 2019-06-05T06:48:06.348Z
Hash: efd3de5e2da11726f422
Time: 4639ms
chunk {main} main-es2015.js, main-es2015.js.map (main) 10.1 kB [initial] [rendered]
chunk {polyfills} polyfills-es2015.js, polyfills-es2015.js.map (polyfills) 250 kB [initial] [rendered]
chunk {runtime} runtime-es2015.js, runtime-es2015.js.map (runtime) 6.08 kB [entry] [rendered]
chunk {styles} styles-es2015.js, styles-es2015.js.map (styles) 16.7 kB [initial] [rendered]
chunk {vendor} vendor-es2015.js, vendor-es2015.js.map (vendor) 3.61 MB [initial] [rendered]

$ ng build --watch

Date: 2019-06-05T06:48:44.350Z
Hash: 55cc7c8d13a9047850cc
Time: 7073ms
chunk {main} main.js, main.js.map (main) 10.1 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 248 kB [initial] [rendered]
chunk {polyfills-es5} polyfills-es5.js, polyfills-es5.js.map (polyfills-es5) 380 kB [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.08 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 16.7 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 3.61 MB [initial] [rendered]
3 Answers

I had a similar question posted on StackOverflow. I noticed that the bundles were different when running ng build vs. ng build --watch. In case you were wondering why they are different... The ES5 versions of bundles output by ng build support the new Angular 8 differential loading feature. It turns out that differential loading is disabled for ng serve and ng build --watch by default for performance reasons. This Github discussion provides a good explanation of why and workarounds in case you need to use differential loading in these scenarios.

For a different purpose, I faced a kind of same issue : once built, I had to write a file for ASP.NET that would sum up the bundles, so that it could be written by hand in the index.cshtml file.

I simply did a little node script that needs to be ran after each build with the --stats-json flag. Here it is :

const fs = require('fs');

// Don't do if dist not existing
if (!fs.existsSync('./dist')) return;
if (!fs.existsSync('./dist/myProject/stats.json')) return;

// Remove previous file
if (fs.existsSync('./dist/myProject/bundle-chunks.json')) fs.unlinkSync('./dist/myProject/bundle-chunks.json');

// Read file, parse to JSON
const statsStr = fs.readFileSync('./dist/myProject/stats.json').toString();
const statsJson = JSON.parse(statsStr);

// Get corresponding property
const assets = statsJson.assetsByChunkName;

// Transform the object into an array with more information
const payload = Object.keys(assets).reduce((pk, nk) => {
  const key = nk;
  const ext = assets[nk].split('.').pop();
  const path = assets[nk];
  pk.push({ key, ext, path });
  return pk;
}, []);

// Reduce the array to build a JSON object of typ { scripts: [], styles: [] }
const metas = payload.reduce((p, n) => {
  if (n.ext === 'js')
    p.scripts.push(`<script type="text/javascript" src="./${n.path}" ${n.path.includes('polyfill') ? 'nomodule' : ''}></script>`);
  if (n.ext === 'css')
    p.styles.push(`<link rel="stylesheet" href="./${n.path}">`);
  return p;
}, { styles: [], scripts: [] });

// Save in file
fs.writeFileSync('./dist/myProject/bundle-chunks.json', JSON.stringify(metas, null, 2));

// Notify
console.log('Bundle chunks written to bundle-chunks.json file');

// Scripts files are to be added to the end of the body (to incread load time and let the page display itself while loading)
// Style files are to be added to the head of the application.

I solved it by only using a BundleConfig in non-dev environments. I only need BundleConfig in non-dev environment because of the bundles are named with hashes.

I have to use ng build --watch instead of ng build when developing.

Not the best solution, but this will work for me until we have refactored the app so we can use ng serve instead.

    @if (Model.IsDev)
    {
        @{ /* These are produced when running ng build --watch }
        <script src="/Static/dist/runtime.js"></script>
        <script src="/Static/dist/polyfills-es5.js" nomodule></script>
        <script src="/Static/dist/polyfills.js"></script>
        <script src="/Static/dist/scripts.js"></script>
        <script src="/Static/dist/vendor.js"></script>
        <script src="/Static/dist/main.js"></script>
    }
    else
    {
        @{ /* These are produced when running ng build or ng build --prod }
        @Scripts.RenderFormat("<script src='{0}' type='module'></script>", "~/scripts/runtime-es2015")
        @Scripts.RenderFormat("<script src='{0}' type='module'></script>", "~/scripts/polyfills-es2015")
        @Scripts.RenderFormat("<script src='{0}' nomodule></script>", "~/scripts/runtime-es5")
        @Scripts.RenderFormat("<script src='{0}' nomodule></script>", "~/scripts/polyfills-es5")
        @Scripts.Render("scripts")
        @Scripts.RenderFormat("<script src='{0}' type='module'></script>", "~/scripts/vendor-es2015")
        @Scripts.RenderFormat("<script src='{0}' type='module'></script>", "~/scripts/main-es2015")
        @Scripts.RenderFormat("<script src='{0}' nomodule></script>", "~/scripts/vendor-es5")
        @Scripts.RenderFormat("<script src='{0}' nomodule></script>", "~/scripts/main-es5")
    }

My BundleConfig looks like this:

    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles, bool isDevEnv)
        {
            // Already minified by angular-cli
            BundleTable.EnableOptimizations = false;

            if (!isDevEnv)
            {
                bundles.Add(new StyleBundle("~/styles")
                    .Include("~/Static/dist/styles.*"));

                bundles.Add(CreateScriptBundle("runtime-es2015"));
                bundles.Add(CreateScriptBundle("polyfills-es2015"));
                bundles.Add(CreateScriptBundle("runtime-es5"));
                bundles.Add(CreateScriptBundle("polyfills-es5"));
                bundles.Add(CreateScriptBundle("scripts"));
                bundles.Add(CreateScriptBundle("vendor-es2015"));
                bundles.Add(CreateScriptBundle("main-es2015"));
                bundles.Add(CreateScriptBundle("vendor-es5"));
                bundles.Add(CreateScriptBundle("main-es5"));  
            }
        }

        private static Bundle CreateScriptBundle(string name)
        {
            return new ScriptBundle($"~/scripts/{name}")
                .Include($"~/Static/dist/{name}.*");
        }
    }
Related