Tips for effectively utilizing the minify maven plugin for compressing JS and CSS files within an AngularJS application

I have been attempting to compress javascripts and css files within my angularjs application by utilizing the samaxes minify maven plugin. While I can successfully minify all js & css files and create a war file with maven, upon trying to access the app URL, I encounter an error:

Error: [$injector:unpr] Unknown provider: aProvider <- a
, causing the app to malfunction.

Below is the configuration of my pom plugin:

<plugin>
    <groupId>com.samaxes.maven</groupId>
    <artifactId>minify-maven-plugin</artifactId>
    <version>1.7.4</version>
    <executions>
        <execution>
            <id>min-js</id>
            <phase>prepare-package</phase>
            <goals>
                <goal>minify</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <charset>UTF-8</charset>
        <skipMerge>true</skipMerge>
        <cssSourceDir>myapp/styles</cssSourceDir>
        <jsSourceDir>myapp/javascript</jsSourceDir>
        <jsEngine>CLOSURE</jsEngine>
        <closureLanguage>ECMASCRIPT5</closureLanguage>
        <closureAngularPass>true</closureAngularPass>
        <nosuffix>true</nosuffix>
        <webappTargetDir>${project.build.directory}/minify</webappTargetDir>
        <cssSourceIncludes>
            <cssSourceInclude>**/*.css</cssSourceInclude>
        </cssSourceIncludes>
        <cssSourceExcludes>
            <cssSourceExclude>**/*.min.css</cssSourceExclude>
        </cssSourceExcludes>
        <jsSourceIncludes>
            <jsSourceInclude>**/*.js</jsSourceInclude>
        </jsSourceIncludes>
        <jsSourceExcludes>
            <jsSourceExclude>**/*.min.js</jsSourceExclude>
        </jsSourceExcludes>
    </configuration>

</plugin>

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.4</version>
    <configuration>
        <webResources>
            <resource>
                <directory>${project.build.directory}/minify</directory>
            </resource>
        </webResources>
    </configuration>
</plugin>

Directory structure:

Structure of my controllers:

'use strict';

angular.module('myApp').controller('MyController', function($scope, $filter, $location, $interval, ngTableParams, $modal, $transition, myService, $timeout) {
   ...
});

Error in Chrome console:

Are there any alternatives that support the minification of angularjs apps apart from the samaxes minify maven plugin? Any assistance on effectively minifying js and css within my angularjs app would be greatly appreciated.

Answer №1

You're making progress in the right direction.

Remember, when you minify a JavaScript code for a controller, all function arguments will also be minified. This can cause issues with the dependency injector not being able to properly identify services.

To solve this problem, you can annotate the function with the names of the dependencies as strings, which will prevent them from being minified. There are two methods to do this:

(1.) Add a $inject property to the controller function containing an array of strings. For example:

function MyController($scope, $filter, $location, $interval, ngTableParams, $modal, $transition, myService, $timeout) {...}
MyController.$inject = ['$scope', '$filter', '$location', '$interval', 'ngTableParams', '$modal', '$transition', 'myService', '$timeout'];

(2.) Use inline annotation where instead of just the function, provide an array. In your case it would look like:

angular.module('myApp').controller('MyController', ['$scope', '$filter', '$location', '$interval', 'ngTableParams', '$modal', '$transition', 'myService', '$timeout', function($scope, $filter, $location, $interval, ngTableParams, $modal, $transition, myService, $timeout) {
   ...
}]);

For more information, refer to the "A Note on Minification" section of this tutorial.

Answer №2

It's important to watch out for reserved words in mvn, such as 'then' and 'catch'.

$http.get('some.json').then(convertResponse).catch(throwError);

You could potentially rewrite it as:

$http.get('some.json')['then'](convertResponse)['catch'](throwError);

If anyone has a better solution, please share as this code seems cumbersome.

For more information, check out Missing name after . operator YUI Compressor for socket.io js files

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

What is the best way to display information from a Django model using a React frontend?

Currently, I am in the process of developing a personal portfolio website using Django for the backend and React for the frontend components. Within this project, I have set up Django tables to store my education history, work experiences, skills, and port ...

How can labels be added when mapping over JSON data?

If I have JSON data structured like this: { "siteCode": "S01", "modelCode": "M001", "modelDesc": "Desc01", "price": 100 "status": "A", "startDate": "Ma ...

When a div is created outside of the viewport, the overflow scroll feature will fail to function properly

I am currently working on developing a full screen slider with a unique feature on the last slide: a horizontal scrolling area. To achieve a smooth animation, I am using CSS translations to bring the div within the viewport. Oddly enough, the scrollbar do ...

jQuery show/hide functionality allows you to toggle the visibility of elements

I am looking to create a toggle button that expands the menu-wrapper width and hides the sidebar when clicked. Here is the initial CSS styling: #my-wrapper { Width:500px; } #sidebar-wrapper { width:200px; } Upon clicking the button, the CSS will update ...

Can an ng-switch be implemented directly on a select dropdown option?

Has anyone tried implementing an ng-switch with a <select> -> <option> set up like this before?: <select ng-model="form.permitLocality" ng-switch on="localityTypeRadio"> <option ng-switch-when="County" ng-repeat="county in coun ...

Dealing with the information received from a PHP response during an AJAX request using JavaScript

Here is my PHP script <?php //establishing connection to the server //selecting the database $temporaryArray = array(); $counter = 0; $result = mysql_query("some query"); while($row = mysql_fetch_assoc($result)) { $temporaryArray["$counter"]= $row[" ...

Securely store passwords in JavaScript for future use

We are in the process of creating a web application that requires decrypting data stored on our server using the user's password. Our objective is to avoid repeatedly asking the user for their password, so we are considering storing the password in a ...

Tips for validating user input within a specific range in React?

I need to restrict user input in an input field to a number range defined by minimum and maximum values. I am working on this functionality using React/Next js. <Input value={tripCoverage} onChange={(e) => { const value = e.target.v ...

Assigning input array values with jQuery

I'm currently working on incorporating HTML input arrays. <input type="text" name="firstName[]" id="firstName[]"> I also need to populate another form that looks like this: <form id="tempForm"> <input type="text" name="userName" i ...

Encountering a rollbackFailedOptional error during the NPM Install process

When attempting to use various command prompts like Windows Powershell, command prompt as an admin, and bash CMD, I encountered the same error message after trying to run npm install: npm install npm@latest -g The specific error message was: [...] / ro ...

Exploring the potential of utilizing functions in express.js to take advantage of the "locals"

Having experience with Rails/Sinatra, I am accustomed to using helper functions in my view files. However, incorporating this functionality into express.js has proven to be quite challenging. You can include locals automatically like this... app.set("nam ...

What is the best way to ensure that all website users receive the same update at the same time using AngularJS and Firebase?

Imagine a scenario where I and my 3 friends are accessing the same website from different computers simultaneously. Each of us has a profile stored in an array like this: $scope.profilesRanking = [ {name:"Bob", score: 3000}, {name:"John", score: 2 ...

Problem with Loading OBJ Files in THREE.JS

I'm having difficulties with the OBJ Loader in THREE.JS. Here is the code I've written: //Setting up the scene scene = new THREE.Scene(); //Creating the camera camera = new THREE.PerspectiveCamera(60, window.innerWidth/window.innerHeight, ...

Undefined method error encountered within Vue.js nested ref structure

My component structure is three levels deep and it's set up like this: - container - section-1 // section1Ref - form-1 // form1Ref The submit method in the container component will call the submit method in section-1 using this.$refs.section1R ...

Create the transformation matrix for the Autodesk model

Can someone provide information about the following two matrices and their purposes? placementTransform (1 x 12) refPointTransform (1 x 16) I believe they may be related to translating (Tx, Ty, Tz) or rotating (Rx, Ry, Rz) 3D objects, but I am unsure du ...

Tips on how to increase and update the index value by 2 within an ngFor loop while maintaining a fixed format

I have a specific template layout that displays only two items in each row as shown below. I want to use the ngFor directive to iterate through them: <div class="row" *ngFor="let item of cityCodes; let i = index"> <div class="col-6" (click)= ...

The issue with Three.js responsive canvas is that it fails to properly adjust the size of the

I'm currently working on a threejs basic scene and attempting to create a responsive canvas for a full-screen experience. However, the mesh inside the scene is not resizing correctly as expected. Instead of remaining a cube, it distorts into a rectang ...

Why Doesn't Vue Scoped SCSS Support the Display Flex Property?

Greetings! I am working on a Vue Formulate form and here is the code snippet: <template> <div class="repeatable-container"> <FormulateForm> <FormulateInput type="text" label="strength" placeh ...

Searching a JSON document to retrieve the position within an array

Attempting to query a JSON file in order to adjust the position of an array. For instance, here is a snippet from the JSON file: { "result": [{ "summonerLevel": "0", "summonerID": "0", "summonerName": "", "summonerIcon": ...

Building a Next.js application that supports both Javascript and Typescript

I currently have a Next.js app that is written in Javascript, but I am looking to transition to writing new code in Typescript. To add Typescript to my project, I tried creating a tsconfig.json file at the project root and then ran npm install --save-dev ...