Search code examples
vue.jsnpmwebpacksass

How do I configure webpack to ignore my non-existing resource in scss?


I receive an error when compiling my scss file.

In the .scss file I have:

    body {
      background-image: url("/static/background.webp");
    }

This is the error I get:

    error  in ./src/scss/general.scss?vue&type=style&index=0&prod&lang=scss&external
    Syntax Error: HookWebpackError: Cannot find module './static/background.webp'

I have a webserver that will generate this background.webp but it doesn't exist in this project.
My solution is to either put a temporary file in my project so it can be resolved or a cleaner approach would be to configure the project to ignore this file.

I need help with how to make the scss loader ignore this file.

I am using webpack 5, node 16/npm 8, vue 2 and building with vue-cli-service 5.


Solution

  • The error you are receiving is due to the Webpack configuration from Vue CLI whereby it includes css-loader. It describes itself as:

    The css-loader interprets @import and url() like import/require() and will resolve them.

    Thus you should consider altering the css-loader configuration of your project, by using the css.loaderOptions option in vue.config.js.

    For example, to completely disable css-loader's resolution of any url() or image-set() functions, set url to false:

    const { defineConfig } = require('@vue/cli-service');
    
    module.exports = defineConfig({
      css: {
        loaderOptions: {
          css: {
            url: false
          },
        },
      },
    });
    

    Or, for only the /static/background.webp value, pass an object with the filter property as a function that passes false for the given value:

    const { defineConfig } = require('@vue/cli-service');
    
    module.exports = defineConfig({
      css: {
        loaderOptions: {
          css: {
            url: {
              filter(url) {
                return url !== '/static/background.webp';
              },
            },
          },
        },
      },
    });