typescriptwebpackvuejs3vue-cli-3

vue cli 3 ignore background image urls


Is it possible in vue cli 3 with typescript to ignore background image urls when compiling scss files? I am writing a SPA which will sit as a page inside a parent site and all the background images will be coming from the parent site so in my scss file I have things like:

.loading {
      background: transparent url(/images/loading/yellow-spinner.svg) center center no-repeat;
}

Where the image is served in the main site and not in the SPA. However this fails to compile as it can't find the image. I had a look at the static assets and it says to put a @ in front of the url but that didn't work either and neither did changing it to ~@.

It would work if I copied the image into the SPA and used a relative path to it in the SCSS, but then that would copy the image into a img folder and change the url in the compiled css which I don't want as it is duplicating resources which may have been cached if they user had visited the parent site.

I have also tried to change the directory of the file-loader to match the parent site by using the following:

configureWebpack: {
    module: {
        rules: [
            {
                test: /\.(png|jpg|gif|svg)$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            outputPath: 'images/',
                            publicPath: 'images/',
                            name: '[path][name].[ext]',
                        },
                    }
                ]
            },
        ]
    },
}

But as soon as I add this, I get the following error (which is the also the error when I try to use the @ and ~):

Syntax Error: HookWebpackError: Cannot find module '../../Images/Loading/red-spinner.svg'

Please note I have added the svg typescript shim which got rid of the module error for the relative path without the added config

With webpack we just copied images using the copy webpack plugin and it seemed to ignore the urls when the scss compiled - isn't there an option for this with vue cli? I also tried using the copy plugin which worked fine, but it still compiled the images with file loader


Solution

  • So to ignore the urls in your scss files you need to add the following option in your vue.config:

    css: {
        loaderOptions: {
            css: {
                url: false,
            },
        },
    },