Angular Code Splitting with Webpack

My current project setup is causing some loading issues due to the large download size of Angular Material. As a result, a white screen remains loading for around 45 seconds. I have attempted to implement code splitting to enhance the loading speed of my application, but I am encountering errors in the process. Unfortunately, code splitting does not seem to be effective in my case.

core/app.module.js

'use strict';

require.ensure([], function (require) {

    require('angular/angular.min');
    require('angular-aria/angular-aria.min');
    require('angular-animate/angular-animate.min');
    require('angular-ui-router/release/angular-ui-router.min');

}, 'common');

var page1Module = require('./../page1/page1.module');
var page2Module = require('./../page2/page2.module');
var appRunBlock = require('./app.run');
var appConfig = require('./app.config');

var moduleName = 'app';

var app = angular.module(moduleName, [
        'ui.router',
        page1Module,
        page2Module
    ])
    .config(appConfig)
    .run(appRunBlock);

module.exports = moduleName;

page1/page1.module.js

'use strict';

require.ensure([], function (require) {

    require('angular-material/modules/js/core/core.min.js');
    require('angular-material/modules/js/core/core.min.css');
    require('angular-material/modules/js/core/default-theme.js');
    require('angular-material/modules/js/button/button.min.js');
    require('angular-material/modules/js/button/button.min.css');

}, 'page1');

var page1Route = require('./page1.route');
var page1Controller = require('./page1.controller');

var moduleName = 'app.page1';

angular.module(moduleName, [
        'material.components.button'
    ])
    .config(page1Route)
    .controller('Page1Controller', page1Controller);

module.exports = moduleName;

page2/page2.module.js

'use strict';

require.ensure([], function (require) {

    require('angular-material/modules/js/core/core.min.js');
    require.include('angular-material/modules/js/core/core.min.css');
    require.include('angular-material/modules/js/core/default-theme.js');
    require('angular-material/modules/js/toolbar/toolbar.min.js');
    require('angular-material/modules/js/toolbar/toolbar.min.css');
    require('angular-material/modules/js/content/content.min.js');
    require('angular-material/modules/js/content/content.min.css');
    require('angular-material/modules/js/input/input.min.js');
    require('angular-material/modules/js/input/input.min.css');

}, 'page2');

var page2Route = require('./page2.route');
var page2Controller = require('./page2.controller');

var moduleName = 'app.page2';

angular.module(moduleName, [
        'material.components.toolbar',
        'material.components.content',
        'material.components.input'
    ])
    .config(page2Route)
    .controller('Page2Controller', page2Controller);

module.exports = moduleName;

I have included my webpack.config.js

var webpack = require('webpack');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var path = require('path');

var webpack_config = {
    context: path.join(__dirname + '/app'),
    entry: {
        app: './core/app.module.js'
    },
    output: {
        path: path.join(__dirname + '/release'),
        publicPath: 'http://localhost:8080/',
        filename: '/js/[name].js',
        chunkFilename: '/js/[name].js'
    },
    module: {
        loaders: [
            {
                test: /\.css$/,
                exclude: 'node_modules',
                loader: 'style!css'
            },
            {
                test: /\.scss$/,
                exclude: 'node_modules',
                loader: 'style!css!sass'
            },
            {
                test: /\.html$/,
                exclude: 'node_modules',
                loader: 'ngtemplate?relativeTo=' + (path.join(__dirname, './app')) + '/!html?' +
                JSON.stringify({attrs: ['img:src', 'img:ng-src', 'md-icon:md-svg-src']})
            }
        ]
    },
    plugins: [
        new CopyWebpackPlugin([
            {from: './index.html', to: './index.html'}
        ])
    ],
    devServer: {
        contentBase: path.resolve('./release')
    },
    watch: true
};

module.exports = webpack_config;

I have attempted to utilize require.include within require.ensure to load my files as needed, but it has not been successful. I have also added my library path in the require.ensure([]) array without success.

The only effective solution so far has been to create a second entry in webpack.config.js and consolidate all my libraries into a common chunk named 'vendor', or to use require() instead of require.ensure().

Due to the large size of the Angular Material library (approximately 1.5 MB), the loading time ranges from 30 seconds to 1 minute. The white screen during loading until all libraries are loaded has prompted me to explore code splitting. I am currently using webpack-dev-server and encountering the following errors https://i.sstatic.net/mK9IL.png

I would greatly appreciate any assistance. Thank you.

Answer №1

After some research, I discovered the importance of utilizing ocLazyLoading for dynamically loading modules. It became clear that understanding the location and trigger point for loading modules, templates, or libraries is vital. In my particular scenario, I found that implementing ocLazyLoading on the route was the solution for loading my modules effectively.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue JS: Breathing Life into Your Elements

Incorporating Vue-Router and Vuex, I have successfully implemented a Users Profile Component that fetches user information by extracting the username parameter from a router-link. For example, <router-link :to="{name: 'user', params: { usernam ...

Is the JQuery ajax xhr fully completed before it begins?

Having a long script that can take a few minutes to execute, I decided to create a progress bar to display the current state. However, I encountered a problem where xhr evt.loaded/evt.total (30/30) returns 1 (100%) before the long script starts executing. ...

The $http service fails to evaluate Angular JS expressions

A snippet from Script.js: var app = angular .module("myModule", []) .controller("myController", function ($scope, $http) { $http.get( url: 'EmployeeService.asmx/GetAllEmployees' ) .then(function (response) ...

I am experiencing an issue where the tooltip does not appear when I click the icon. What adjustments can be made to the code to ensure that the tooltip

I have created a feature to copy abbreviation definitions when the clipboard icon is clicked. A tooltip displaying 'Copied' should appear after clicking the icon, but for some reason, it's not visible. Here's the code: $(document).re ...

Are certain browsers unable to play dynamically generated HTML5 audio files?

While working on my project, I encountered an issue with creating and controlling an audio element in JavaScript. The element works perfectly fine in Firefox, Chrome, and Opera; however, it fails to function properly in IE and Safari. In these browsers, ...

Can an image map area be identified using radial coordinates?

While I have experience with online Imagemap Generators for rectangular or circular areas in HTML pages, things get a bit tricky when dealing with pie-shaped sections. When trying to make each pie slice a separate area, the image map code generated by thes ...

Click event not triggering on inner div element

Can anyone help me with a simple task I'm attempting to do? The ng-click is not functioning as expected. Could there be an issue with divs nested within another div, or am I just too tired to figure this out? Although the specific item affected is not ...

jQuery load() issue

$('form.comment_form').submit(function(e) { e.preventDefault(); var $form = $(this); $.ajax({ url : 'inc/process-form.php', type: 'POST', cache: true, data:({ comment ...

Tips for ensuring all images are the same size within a div element

https://i.stack.imgur.com/EkmWq.jpg Is there a way to make sure all the images fit perfectly inside their respective border boxes without appearing stretched? I've tried setting fixed height and width within a div, but they always end up looking off. ...

Is there a way to input the Sno data into the database in ascending order?

function table_insert(lease_ids){ var lease_id=lease_ids+1; var table = document.getElementById('table_data123'), rows = table.getElementsByTagName('tr'), i, j, cells, customerId; for (i = 0, j = rows.le ...

TextAngular failing to replace &nbsp character

I am currently using textAngular within a div that has a character counter feature. However, I have encountered an issue where a space ( ) is being counted as 6 characters instead of just one. Despite trying various regex patterns to convert this spec ...

Display different images based on user selection in vue.js

I am new to working with vue.js and I'm facing a challenge. My goal is to display images of NBA players based on the selected criteria using vue.js. For instance, if the Dunk contest champion is chosen, only images of Kobe and Jordan should be display ...

Update the document by sending the data and making changes based on the AJAX response

Currently, I am avoiding using jQuery and trying to work with the following code in PHP: <?php header ( 'Content-Type: text/xml; charset=utf-8' ); $con = @mysql_connect ( "localhost", "root", "" ) or die ( "Couldn't connect to database" ...

Guide on transferring files between Node.js/Express servers from receiving files at Server A to sending files to Server B

Currently, I'm tackling node.js express servers and I've hit a roadblock! Despite my efforts to scour the documentation and other resources, I can't seem to find the right solution. Here's what I need to accomplish: Receive 2-3 PDF ...

ms-card malfunctioning due to data issues

I'm facing difficulties in transferring the data to the template. Although I can access the data in HTML using vm.maquinas and maquina, I am unable to pass it to the TEMPLATE through ng-model. Information about ms-cards was not abundant. Module ang ...

Ways to adjust the visibility of a div element multiple times using javascript and css

I implemented a popup feature in my application: <div id="modal"></div> let modal = document.getElementById('modal') modal.innerHTML = ` <button class="close-button" onclick="close_modal()" ...

Create a JavaScript file that will generate a map based on data from an SQL

I am currently working on developing a Leaflet map with numerous markers. To streamline the process of updating the map, I have stored all the markers in a MySQL database. A PHP script is utilized to retrieve the data from the database, format it in a way ...

Is there a way to retrieve a large number of users through an API using async await?

I am trying to retrieve all users from an API and I want to identify which user receives the highest payment. For instance let users=['tom','jenny','smith','Joe'] async function getUsers() { let response = awa ...

PHP Error - Noticed a non-existent constant 'x' being used in the code, assumed it to be 'x

How to Retrieve Data from a Table, Pass it to the Controller in JSON Format, and Display it in a View Using AngularJS I am looking to extract data from a controller's json-encoded variable and showcase it on a view page through angularjs <div cla ...

Changing the background color of MUI TextField for autocomplete suggestions

I am currently facing an issue with the background color of auto-complete fields in my React.js and Material UI app. https://i.sstatic.net/lZdDh.png The auto-complete fields are adding a white background which is unnecessary. Interestingly, when I manua ...