Preventing the Vue compiler from managing static assets: A step-by-step guide

In my Vue 3 application, I have a variety of static assets that are organized in their own file structure separate from the app's source directory. Fortunately, my web server is configured to serve files from both the Vue build directory and the static assets directory without any issues.

However, the Vue compiler seems to be struggling with this setup. It attempts to resolve paths and copy assets to the build directory. This becomes problematic when using absolute paths as the compiler fails to locate the assets and crashes.

Desired Outcome

I prefer for the Vue compiler to only generate css and js files, rather than including static files in the build directory. When the compiler encounters a reference to a static file like:

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

it should not try to move /images/background.jpg to the build directory. Instead, it should assume that I have already placed the file in its correct location.

Current Configuration

Currently, my setup involves using Vue 3 and Webpack 5. My webpack.config.js looks like this:

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' ),
    },
}

Answer №1

To prevent Webpack from emitting assets, you must configure it accordingly.

By default, asset/resource modules will be emitted with a [hash][ext][query] filename into the output directory.

If you do not specify how to handle asset resources in your webpack configuration, a file will be emitted for each resource.

Additionally, keep in mind that vue-loader does not alter absolute paths:

Vue will retain absolute path specifications for static asset URLs as they are specified.

To address this issue, ensure you include a rule in your webpack configuration targeting your specific asset types. This rule should be placed at the beginning (the last item) of your rules array.

//...
module: {
    rules: [
      //...
      {
        test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i,
        type: 'asset/resource',
        generator: {
          emit: false,
        },
      },
    ],
},
//...

For further details, refer to the webpack documentation here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Convert millimeters to inches with a unique AngularJS filter that activates on click

I am currently working on a UI that requires users to enter dimensions for width and height. Within the UI, there are 2 buttons available - one for 'mm' and the other for 'inches'. When either of these buttons is pressed, the active cl ...

Response received from the server

I am looking to display server response error messages within a form after submission. By using the following code in my JavaScript, I am able to retrieve the error message: .error(function (data, status, header, config) { $scope.postDataSuccessfully ...

Clearly state the action of the form

I have utilized html, JavaScript, CSS, and JQuery to create a website template. Within this template, there is a file called contact.js that contains the ajax code for handling forms: $(function() { submitSuccess: function($form, event) { ...

React application triggers `OnKeyDown` event just once

Hey there! I'm diving into the world of web development and could use some help. My current challenge involves manipulating input data based on key combinations like ctr + ArrowUp (increase) and ctr + ArrowDown (decrease). The dynamic part should be h ...

Tips on how to define an ajax request for the PHP section that is being managed

I recently started using ajax calls to retrieve information from php files and I have 7 elements in my html that trigger these calls. I've created 7 separate php files to handle each ajax call, like so: html part: <a style="cursor:pointer;" id="o ...

A guide on extracting the current website URL in a React application

I wanted to find a method to duplicate the text from a URL so that users could easily share the link with others. ...

Can someone explain to me how this AngularJS factory example functions? I have some uncertainty

As a beginner in AngularJS, I am currently studying it through a tutorial and have some questions regarding the use of the factory in Angular. From what I understand, a factory is a pattern that creates objects on request. In the example provided, we see ...

Obtain the content of every cell in a constantly updating table

I have created a dynamic table as shown below: <table id="sort" class="table"> <thead> <tr> <th>Column Name from DB*</th> <th>Record Le ...

Utilizing a universal JavaScript array within the jQuery document(ready) function

After using jsRender to render the following HTML template, I encountered an issue with passing data values through jQuery selectors when submitting a form via AJAX. <div class="noteActions top" style="z-index: 3;"> <span onclick="noteAction(&a ...

React fails to trigger a re-render despite updating the state following an API call

Recently, I started working with React and attempted to retrieve data from my API. However, changing the state does not trigger a re-render of the component. Inside the useEffect function in my component, I have code that fetches the API and then sets the ...

express node struggling to locate bootstrap.js file

I am working with a specific directory structure within my project: projectName | -.sencha/ | - app/ | - view | - controller | - store | - saas | - server/ | -server.js ...

What causes an error when attempting to add a new user to the database?

Currently, I am delving into the world of Mongodb. To kick things off, I initiated by executing npm install --save mongoose uuid within the confines of Terminal. The primary objective of my project revolves around storing user information in the database. ...

Develop a JavaScript application that contains a collection of strings, and efficiently sorts them with a time complexity of O(nlog n)

Seeking assistance in developing a JavaScript program that contains an array of strings and must sort them efficiently in O(nlog n) time. Grateful for any guidance... ...

Eliminate spaces within a string using JavaScript

In my quest for knowledge about trimming strings in JavaScript, I came across this intriguing discussion with a regex-based solution. After learning from the thread, I was under the assumption that trim would eliminate the space between "Hello" and "World ...

What is the best way to automatically remove a Firebase database entry when a user has been inactive for a period of time, without logging out but simply not accessing the page for an extended duration?

Currently, when a user clicks 'logout', their session is terminated, and a database entry is removed. All other users can see that database entry, so the objective is for users to view each other's data only while they are logged in. For in ...

What is the best way to retrieve $scope in AngularJS using JavaScript?

Check out this demo on JSFiddle: http://jsfiddle.net/altermind/yak10smq/1/ In the controller 'EntrynewCtrl', I am trying to declare a variable called 'appetite' and pass it to a JavaScript function like this: <script> var ...

Exploring the colors of legend navigation icons in Google Pie charts

Is there a way to customize the color of the navigation links in Google pie charts (specifically the blue text in the bottom right corner)? https://i.sstatic.net/Hk591.png ...

Stop calling API after a certain time period in vue.js

Imagine a situation where the GET API call requires approximately 1 minute to retrieve the most recent data after being updated by INSERT/UPDATE API calls. Suppose a user modifies certain fields in the user interface and triggers an UPDATE call, which the ...

Modifying the User Model in Sails.js results in an automatic password update

/** * User.js * * @description :: The User model handles user data, including hash functions for password security. * @docs :: http://sailsjs.org/#!documentation/models */ var bcryptjs = require('bcryptjs'); function hashPassword(values, ...

Trigger a function when <a> is clicked, which will then increment the count by one and reflect this change in the database

The database generates the content of this div ordered by a count number called "cts". Whenever I click on the div, I want the "cts" number to increase by one, and then update the change in the database. This will result in the content changing accordingly ...