What is the best webpack configuration for an AngularJS 1.x application in webpack 2?

Looking to start a new Angular 1.x app with webpack 2 from scratch.

Struggling to find the perfect configuration for webpack.config, specifically for optimal entry and output settings for production (where all code, styles, and templates are minified and gzipped without any redundancy).

The main issue lies in how to configure webpack.config to recognize all partials within my project's folder structure, similar to these:

https://i.sstatic.net/nuPoc.png

Here is my current config file (unable to view subfolders):

var HtmlWebpackPlugin = require( 'html-webpack-plugin' );
var ExtractTextPlugin = require( 'extract-text-webpack-plugin' );
var path = require( 'path' );

module.exports = {
    devServer: {
        compress: true,
        contentBase: path.join( __dirname, '/dist' ),
        open: true,
        port: 9000,
        stats: 'errors-only'
    },
    entry: './src/app.js',
    output: {
        path: path.join( __dirname, '/dist' ),
        filename: 'app.bundle.js'
    },
    module: {
        rules: [ {
            test: /\.scss$/,
            use: ExtractTextPlugin.extract( {
                fallback: 'style-loader',
                use: [
                    'css-loader',
                    'sass-loader'
                ],
                publicPath: '/dist'
            } )
        } ]
    },
    plugins: [
        new HtmlWebpackPlugin( {
            hash: true,
            minify: { collapseWhitespace: true },
            template: './src/index.html',
            title: 'Prov'
        } ),
        new ExtractTextPlugin( {
            filename: 'main.css',
            allChunks: true
        } )
    ]
};

Answer №1

Keep in mind that this solution is not exhaustive, as there are numerous optimizations that can be implemented on the frontend. The code snippets provided here are kept relatively brief.

When using webpack, there are several approaches you can take to incorporate partials into your app.js.

Method 1
You can import or require your partials within app.js like this:

app.js

var angular = require('angular');
var proverbList = require('./proverb/list/proverb.list');
// require other components

// set up your app as usual

This method allows the app.bundle.js file to include your component JavaScript files in the main bundle. Additionally, you can utilize html-loader to include templates in the final bundle.

However, this approach has its drawbacks as it simply creates a large bundle.js file (which may not optimize multiple downloads with http2 or allow loading of components/files on user demand).

Method 2
Importing partials as separate entry files into your webpack bundle:

webpack.config.js

const globby = require('globby');
const sourceDir = 'src';
var webpackentry = {
    app: `${__dirname}/src/app.js`
};

const glob = globby.sync(`${__dirname}/${sourceDir}/**/*.js`)
    .map((file)=>{
    let name = file.split('/').pop().replace('.js', '');
    webpackentry[name] = file;
});


const config = {
  entry: webpackentry,
  ...
}

The second method might seem unconventional but it can be helpful if you need to split all your partials as <script> tags in your HTML (for instance, if your team uses that method to include directives/components/controllers), or if you have an app-2.bundle.js.

Method 3
Utilize CommonsChunkPlugin:

webpack.config.js

let webpackentry = {
  vendor: [
   'module1',
   'module2',
   'module3',
  ]
}
...
plugins: [
  new webpack.optimize.CommonsChunkPlugin({
    name: ['vendor'] //... add other modules
  })
]

The CommonsChunkPlugin enables webpack to analyze your entry files and identify common modules shared among them. This means that even if you import module1 in different files, it will only be compiled once in the final bundle.

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

Tips for extracting the data from a resolved promise

As a beginner in Angular, I am facing some difficulties in figuring out how to extract the value from a resolved promise. In my code, I have used $q.all([element1.$promise, e2.$promise]). This returns element1 as a JSON object. However, for element2 which ...

Encountered problem with AJAX in Java: Unable to assign value to property 'innerHTML' as it is null

Recently, I've been eager to dive into learning AJAX and decided to create an app following a tutorial similar to the one provided here. However, after painstakingly replicating the code, I found that it's not working as expected. Despite multipl ...

The attempt to run 'readAsBinaryString' on 'FileReader' was unsuccessful. The first parameter is not the expected type 'Blob'

I am currently working on parsing an xls file. You can find the file by clicking on the following link: However, I am encountering an error that says: 'Failed to execute 'readAsBinaryString' on 'FileReader': parameter 1 is not of ...

Javascript clock problem, kick off on click

Currently working on a game and in need of a counter that starts when clicked and stops at 00 (From 1m to 00). It is currently starting onload and cycles back to start when it reaches 00. HTML: <body> <div> <div class="timer" >Battle t ...

Effective ways to transmit a variable array from an HTML document to a PHP server

Is there a better method for transferring a variable array from HTML to PHP? I attempted to use the serialize function, but it doesn't seem to be functioning correctly. Any suggestions would be greatly appreciated. //HTML var arrayTextAreasNames = [ ...

Learn the steps to activate on-page editing feature!

Is there a way to make a section of a webpage editable when a button is clicked? (e.g. edit & view on the same page) For instance, imagine you could click "edit" on this very page (the one you are currently reading), and the title and content become edita ...

What is the best way to generate a new DIV every time a button is clicked?

I am attempting to make a square DIV that is red and measures 100x100 pixels. Each time a button is clicked, I want the square to be created. However, the code I have written is not functioning properly: <html> <title> Create New Div ...

Sending asynchronous data to a child component in Angular 2

Having trouble with passing asynchronous data to a child component. I am attempting to create a dynamic form generator, but I encounter an issue when trying to fetch JSON data via an Observable and then passing it to the child component. Service: generat ...

Using Angular to make GET requests with JSON data in PHP

Seeking assistance with connecting Angular frontend to PHP backend. Upon calling the service, I am receiving an empty array in the console. Controller: angular.module('pageModule') .controller('pageController', ['$scope', &a ...

Troubleshooting: Issues with the angular.isObject() function

The angular.isObject method provided by Angular is not functioning correctly in my Angular template file. I have implemented this function in my template as shown below: <div class="row no-padding" ng-if="angular.isString(student)"> {{student}} < ...

Angular: Maximizing Input and Output

I'm having trouble with the function displaying within the input field. My goal is to simply allow the user to enter a name and have it displayed back to them. HTML: <div ng-app = "mainApp" ng-controller = "studentController"> <tr> < ...

Use jasmine's httpbackend to create a mock response for any given URL

Presently, I am constructing a test for my Angular application utilizing Jasmine. My goal is to simulate the api call in order to receive certain data. However, the api call in my controller is as follows: $scope.getSubjects = -> $http.get "/api/stu ...

Do I have to cram all the content onto a single page just to use a scroll effect?

I'm currently facing a dilemma as I work on building my portfolio. My goal is to primarily use html5 and css3, along with a bit of js, jquery, and other tools if necessary. Although I am not an expert in web development, I wanted to push myself to cre ...

What could be causing the issues with SSL certificates when using Node.js/Express-TypeScript?

I'm currently in the process of transitioning a project's backend from JavaScript (Node.js/Express) to TypeScript. However, I've encountered an unusual issue where FS's readFileSync is unable to access the key.pem or cert.pem files in t ...

Managing object methods in ReactJS state

Currently, I am utilizing the Google Maps API and have the following piece of code implemented: class App extends React.Component { state = { polygon: null, }; checkPoly() { if (this.state. ...

Can Angular validate other input fields?

Is it possible to modify this directive so that if the user changes the IP Address to "192.168.3.10" or the Gateway to "192.168.3.1", all three fields are marked as invalid? The desired behavior is for one field being marked as invalid to trigger the othe ...

How to render a div in HTML with full CSS styling applied

I'm currently working on a project using asp.net MVC. My goal is to print a div with all the CSS styles applied, which may contain one or more nested divs. Despite trying various JavaScript print codes, I have not been successful. The page I want to p ...

Using a custom function from the controller to apply an AngularJS filter

I need help filtering a table based on age using conditions of less than and greater than 25 years. Click here to see the demonstration The filter function is not working correctly. It returns no results for ages less than 25, and it returns ages 44 and ...

Filter a Vue list based on a checkbox that can be either checked or unchecked

I am currently working on my Vue app and aiming to filter a list to display only entries that have been moderated. However, I am encountering an issue where when the checkbox is checked, I receive all the results that are true, and when the checkbox is un ...

Mysterious Loop in JavaScript Unfolding with Three.Js

In order to expand my knowledge of Angular and Three.Js, I am currently working on a prototype SPA that showcases different 3D elements rotating. There are several Angular templates accessible through a navigation menu, each displaying unique rotating elem ...