How to load split chunks in angular production?

403 views Asked by At

I am using custom webpack configuration in my angular 8 project to split my each npm package into separate chunks. When i am uploading the dist folder on my aws server the browser is not fetching the split chunks. Does anyone has a solution for this? I read somewhere that we have to use indexTransform to generate index.html according to our webpack configuration but i dont know how to use it. Please help!

I read somewhere that we have to use index transformation to generate index.html according to our webpack configuration but i dont know how to use it. Please help!

1

There are 1 answers

0
Prerna Kakria On

After successfully splitting the vendor file into chunks using custom webpack we have to append each package into script in our index.html file and for this we have to use indexTransform. Firstly, create a file in your root index-html-transform.js and copy the below code in it:

const fs = require('fs');
const node_path = require('path');

const addScript = (path)=>{
    // (path)
    return `<script src="${path}"></script>`
}
module.exports = (targetOptions, indexHtml) =>{
    const i = indexHtml.indexOf('</body>');
    const vendor_path = node_path.resolve(__dirname+`/dist`);
    let vendorScripts = ``;
    fs.readdirSync(vendor_path).forEach((file)=>{
        // (file)
        if(file.indexOf('vendor-')===0){
                vendorScripts+=addScript(file);
        }
    });
    
    return `${indexHtml.slice(0,i)}
            ${vendorScripts}
            ${indexHtml.slice(i)}`;
}

Secondly, add the below line in your angular.json file in under build:

"indexTransform":"./index-html-transform.js",