webpackvue.jsvue-loadervue-clivue-filter

Vue filters not resolved when file outside of project root


If I import a filters file that lives outside of the project directory (registering them with import Vue; Vue.filter(...) I get the error Failed to resolve filter.

If I save a copy of the file inside the app's folder and import it from there, the filter will work, but... I don't want a copy of the same file. The app/build is created with the Webpack Vue-CLI. Not sure how to get around this. I know it's not the structure expected by the webpack build/dev, but I'm confused why the location of the file would affect how the code functions.

\utils\filters.js

import Vue from 'vue';

Vue.filter('useless', value => {
  return value;
});

\apps\my-app\my-component.vue (built with Vue webpack CLI)

<script>
import './../../../utils/filters';
</script>

Is it possible that because the filters.js imports Vue from a different place that it's importing a different version of Vue? Or is there another way to register filters that could be used to get around this?


Solution

  • The reason for this is that Vue.filter() is being called on a different instance of Vue when it is being included based on a different package.json, even if it specifies the same version. There may be a way to tell webpack a way to compile these things differently, but a better approach is to convert the filters to a plugin, with an install script that you pass Vue to, so it's whichever Vue you're already using:

      const vueFilters = {
        install(Vue) {
          Vue.filter('useless', value => {
            return value;
          });
        }
      };
    
      export default vueFilters;