AngularJS ES6语法打包部署后过滤器出现Unknown provider错误排查求助
Hey there, I’ve run into this exact issue countless times—let’s break down what’s going on and how to fix it!
Why This Happens
Your app works perfectly locally because you’re running unminified, unobfuscated code. But when you deploy to the server, your build process is almost certainly minifying (compressing) your JavaScript files. AngularJS relies on variable names to resolve dependencies by default, and minifiers rename variables to short, generic strings (like that mysterious e in your error message). So when your filterByQueryFilter tries to inject a dependency, the minifier has changed the dependency’s variable name, and Angular can’t find the matching provider anymore.
How to Fix It
You need to use Angular’s explicit dependency injection syntax so minifiers don’t break your dependency references. Here are the three most reliable methods:
1. Array Syntax (Most Straightforward)
Define your filter using an array where you list dependency names as strings first, followed by the filter function. Strings don’t get renamed during minification, so Angular can always locate the right providers:
angular.module('myFilters') .filter('filterByQuery', ['$someDependency', function($someDependency) { // Your filter logic here return function(input, query) { // ... filter implementation code }; }]);
2. $inject Property
If you prefer separating your function definition from the filter registration, assign a $inject property to the function, listing dependencies as strings:
function filterByQueryFilter($someDependency) { return function(input, query) { // ... filter implementation code }; } // Explicitly declare dependencies to avoid minification issues filterByQueryFilter.$inject = ['$someDependency']; angular.module('myFilters').filter('filterByQuery', filterByQueryFilter);
3. Build Tool Annotations (For Lazy Folks 😄)
If you use a build tool like Webpack, Gulp, or Grunt, add a special comment (/*@ngInject*/) above your filter function. Tools like ng-annotate will automatically convert your code to use explicit dependency injection during the build process:
/*@ngInject*/ angular.module('myFilters') .filter('filterByQuery', function($someDependency) { return function(input, query) { // ... filter implementation code }; });
Just make sure your build pipeline is set up to process these comments (you’ll need to include the ng-annotate plugin or equivalent tool).
Quick Final Check
Double-check that all your Angular components (filters, controllers, services, etc.) use one of these explicit injection methods. It’s easy to miss one, and that’s usually the root cause of this error.
Once you update your filter code to use explicit dependency injection, redeploy your app, and that frustrating [$injector:unpr] error should vanish!
内容的提问来源于stack exchange,提问作者mTv

