Sunday, 6 November 2022

How to stop the Vue compiler from handling static assets

My Vue 3 app references a number of static assets. The static assets are already set up with their own file structure, which happens to be outside of the app source directory. My web server has been configured for this and happily serves files from both the Vue build directory and the static assets directory.

The Vue compiler, however, is not so happy. When it sees a path, it tries to resolve it and copy the asset to the build directory. If I use an absolute path it cannot find the asset, and crashes and dies.

Requirement

I would like the Vue compiler to only output css and js files. I do not need the static files in the build directory. If the Vue compiler sees a reference to a static file - eg:

<style lang="scss">
.hero {
    background-image: url('/images/background.jpg');
}
</style>

it should not try to resolve /images/background.jpg and copy it to the build directory; it should assume that I have already put the file where it needs to be.

Current setup

I'm using Vue 3 and Webpack 5. My webpack.config.js is

const MiniCssExtractPlugin = require( 'mini-css-extract-plugin' )
const { VueLoaderPlugin } = require( 'vue-loader' )
const path = require( 'path' )

module.exports = {
    entry: './src/index.ts',
    mode: 'production',
    module: {
        rules: [ {
            test: /\.vue$/,
            loader: 'vue-loader'
        }, {
            test: /\.ts$/,
            loader: 'ts-loader',
            exclude: /node_modules/,
            options: {
                appendTsSuffixTo: [ /\.vue$/ ]
            }
        }, {
            test: /\.s?css$/,
            use: [
                MiniCssExtractPlugin.loader,
                'css-loader',
                {
                    loader: "sass-loader",
                    options: {
                        additionalData: '@import "@/util/sass/_index.scss";' // import _index.scss to all Vue components
                    }
                }
            ]
        } ]
    },
    plugins: [
        new MiniCssExtractPlugin( {
            filename: 'style.css'
        } ),
        new VueLoaderPlugin(),
    ],
    resolve: {
        alias: {
            '@': path.resolve( __dirname, 'src' )
        },
        extensions: [ '.ts', '.scss', '.vue' ],
    },
    output: {
        filename: 'app.js',
        path: path.resolve( __dirname, 'build' ),
    },
}


from How to stop the Vue compiler from handling static assets

No comments:

Post a Comment